0

I have an issue while trying to parse a string value using object mapper.

Below is my code,

@Data
@NoArgsConstructor
@AllArgsConstructor    
public class Payload {
    private String id;
    private String message;
}

Then my main class

import com.fasterxml.jackson.databind.ObjectMapper;

public class MyClass {
  public static void main(String args[]) throws Exception {
    
    String payloadText = "{\"id\":\"1\",\"message\":\"Message \"Yes\"\"}";
    ObjectMapper mapper = new ObjectMapper();
    
    Payload p = mapper.readValue(payloadText, Payload.class);
    System.out.println(p);
  }
}

My JSON string contains a word with double quotes "". Looks like because of the same, when I am trying to parse the JSON using ObjectMapper readValue method, it gives me below exception,

    Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected character ('Y' (code 89)): was expecting comma to separate Object entries
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); line: 1, column: 31]
    at com.fasterxml.jackson.core.JsonParser._constructReadException(JsonParser.java:2660)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:741)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:2429)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextFieldName(ReaderBasedJsonParser.java:924)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:317)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:177)
    at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:342)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4917)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3860)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3828)
    at MyClass.main(MyClass.java:9)

I have tried using escape character methods from StringEscapeUtils class, but no use. I also tried using JsonParser feature ALLOW BACKSLASH ESCAPING ANY CHARACTER, still no luck.

Can anyone guide as to how can make the object mapper ignore the backslashes used for skipping double quotes.

Any help or pointers are appreciated.

0

2 Answers 2

4

As you are already aware, Java requires that a double-quote character inside a string constant is escaped with a backslash.

However, JSON also requires that a double-quote character inside a string value is escaped with a backslash. You did not do that. In fact, your string has no backslash characters in it. (The sequence \" is a single double-quote character; there is no actual backslash character in the string data.)

By far the best way to eliminate this confusion is by using a multi-line string:

String payloadText = """
    {"id":"1","message":"Message \\"Yes\\""}
""";

But if you really want to do it all on one line, it would need to be this:

String payloadText = "{\"id\":\"1\",\"message\":\"Message \\\"Yes\\\"\"}";

Note: I have added the closing brace (}) to your JSON content. Without it, you would still get a JsonParseException for a different reason.

Sign up to request clarification or add additional context in comments.

6 Comments

Hey, thanks for your response. I have added that missing } at the end. According to your suggestion, I tried adding those extra escape characters in string and it works with below, String payloadText = "{\"id\":\"1\",\"message\":\"Message \\\"Yes\\\"\"}"; But the question now is how to add those extra \\ in that string at the runtime for JSON to process it.
Tried doing this : Payload p = mapper.readValue(payloadText.replace("\"", "\\\""), Payload.class); but it doesn't work. It says was expecting double-quote to start field name. Any tips on how to manage this ?
Just to give more context. I receive that string as response from another API which is the payloadText string as is without escape characters. I get it like \"Yes\" only
@WebNoob Are you saying that you are receiving a JSON-ish string similar to the payloadText value in your question from an external source? Or are you only receiving a single text value in double-quotes?
Hey VGR, sorry for delayed response. I got that wrong it looks like, the payloadText value itself has \" which in turn should get converted to \\\" during processing. So what you were saying was right that it would need \\\" while in processing.
|
0

at my case I had the same issue and the solution for me was to create an empty constructor for the class that I was receiving from the request.

Like:

Wrong:

public final class CreateContractDto implements Serializable {
    @Serial
    private static final long serialVersionUID = 0L;
    private int clientId;
    private int ownerId;
    
    public CreateContractoDto(int clientId,
                              int ownerId) {
        this.clientId = clientId;
        this.ownerId = ownerId;
    }

    // getters, setters, hash, equals, toString
}

Correct

public final class CreateContractDto implements Serializable {
    @Serial
    private static final long serialVersionUID = 0L;
    private int clientId;
    private int ownerId;
    
    //**************************
    //      EMPTY CONSTRUCTOR
    //**************************
    public CreateContractoDto() {
    }

    public CreateContractoDto(int clientId,
                              int ownerId) {
        this.clientId = clientId;
        this.ownerId = ownerId;
    }

    // getters, setters, hash, equals, toString
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.