如何使用object mapper解析java中的以下json数据?

时间:2018-03-08 10:24:11

标签: java

{
  "a" : "Test",
  "b" : "Got you", /** This data is easily parsable*/
  "c" : "Hello \"Test\" there is a problem" /** Not able to parse this data */
}

我需要在json对象的值内解析带双引号的数据。

我试过JSONObject messageJson = new JSONObject(jsonString);它超越了" \""并将其转换为" " &#34 ;.所以它并没有帮助我。我还使用了杰克逊的ObjectMapper,它不能将值映射到pojo对象,因为它" \" "

1 个答案:

答案 0 :(得分:-1)

你用反斜杠逃脱它。 {“Attribute_1”:“\”test \“”并且JSON无效。

无论如何问题是,当它到达{“Attribute_1”:“”时,解析器认为它已经读取了一个键值对,并抱怨后面的内容不是a或者}}

解决方案:您必须相应地提供json,因此编译器可以为json值转义“”。 将json String写为:

String json = "{\"a\" : \"Test\",\"b\" : \"Got you\",\"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 = "{\"a\" : \"Test\",\"b\" : \"Got you\",\"c\" : \"Hello \\\"Test\\\" there is a problem\"}";
    System.out.println(new ObjectMapper().readValue(json, tr));
}