我正在努力使用jackon将json字符串转换为java对象。这可能是重复的问题,但我无法找到解决此问题的任何方法:
这里是json字符串:
{
"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;
}
尝试使用jackson以这种方式将json转换为对象:
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
mapper.readValue(nodeStr, HierAttributes.class);
我得到以下异常:
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)
有没有什么方法可以让jackson在解析时逃避字段值(""not listed""
)中的其他引号?如何解决这个解析问题?
答案 0 :(得分:3)
第一
接受这是无效的JSON,你必须在杰克逊为你解析它之前改变它。
第二
如果双引号加倍是唯一的问题,那么在将字符串传递给jackson之前使用以下之一预处理该字符串:
newValue = initialValue.replaceAll("\"\"", "\"");
newValue2 = StringUtils.replace(initialValue, "\"\"", "\"\\\"");
我建议在上面的选项2中使用Apache Commons Lang3 StringUtils。