当值包含双引号时,Java jackson ObjectMapper会失败吗?

时间:2017-10-02 12:21:35

标签: java json jackson

我有java字符串(包含json对象)

{"Attribute_1":""test"","Attribute_2":"100"}

当我转换为java对象MyCustomClass时,由于test周围的双引号,我得到运行时错误。我不知道如何逃避内部的双引号 json属性值

ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(requestData, MyCustomClass.class);

错误是

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('t' (code 116)): was expecting comma to separate OBJECT entries
 at [Source: {"Attribute_1":""test"","Attribute_2":"100"} line: 1, column: 12]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1419)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:508)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:437)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:1795)

这不是How to escape double quotes in JSON的重复,因为这是显示问题

1 个答案:

答案 0 :(得分:0)

你正在错误地逃避它。正确的方法是你必须相应地提供json,这样编译器就可以逃避""为json值。 将json String写为:

String json = "{\"c\" : \"Hello \"Test\" there is a problem\"}";

示例测试代码:

public static void main(String[] args) throws Exception {
    TypeReference<HashMap<String, String>> tr = new TypeReference<HashMap<String, String>>() {
    };
    String json = "{\"c\" : \"Hello \"Test\" there is a problem\"}";
    System.out.println(new ObjectMapper().readValue(json, tr));
}