Rahul Sharma
Rahul Sharma

Reputation: 5834

Jackson- Json parsing failure because of extra quotes in values

I am struggling to convert json string to java object using jackon. This might be duplicate question but I couldn't find any solution for this problem:

Here's json string:

{
"hierCD":"B",
"category":"C",
"id":"ty8lre",
"bca":"8543289",
"companyName":""not listed"",
"productLineCD":"CARD"
}

Java Bean:

public class HierAttributes{
protected String id;
protected String bca;
protected String companyName;
protected String productLineCD;
protected String hierCD;
protected String category;
}

Trying to convert json to object using jackson this way:

ObjectMapper mapper = new ObjectMapper(new JsonFactory());
mapper.readValue(nodeStr, HierAttributes.class);

I get below exception:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('n' (code 110)): was expecting comma to separate OBJECT entries
 at [Source: {"hierCD":"B","category":"C","id":"ty8lre","bca":"8543289","companyName":""not listed"","productLineCD":"CARD"}; line: 1, column: 77]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1581)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:533)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:462)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:1957)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextFieldName(ReaderBasedJsonParser.java:770)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:265)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:125)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)

is there any way so jackson will escape additional quotes in field value(""not listed"") while parsing? how to resolve this parsing issue?

Upvotes: 2

Views: 7876

Answers (1)

DwB
DwB

Reputation: 38300

First

Accept that this is not valid JSON and you will have to alter it before jackson will parse it for you.

Second

If doubling of double quotes is the only problem, then preprocess the string with one of the following before passing it to jackson:

  1. Remove the double quoting: newValue = initialValue.replaceAll("\"\"", "\"");
  2. Add backslash to the inner quotes. newValue2 = StringUtils.replace(initialValue, "\"\"", "\"\\\"");

I suggest using Apache Commons Lang3 StringUtils for option 2 above.

Upvotes: 3

Related Questions