如何使用Jackson解析嵌套的转义json?

时间:2019-02-05 09:39:39

标签: java json jackson2

考虑json:

{
    "name": "myName",
    "myNestedJson": "{\"key\":\"value\"}"
}

应解析为类:

public class MyDto {
    String name;
    Attributes myNestedJson;

}

public class Attributes {
    String key;
}

是否可以在不编写流解析器的情况下对其进行解析? (请注意,myNestedJson包含json转义的json字符串)

1 个答案:

答案 0 :(得分:0)

我认为您可以向Attributes添加一个String的构造函数

class Attributes {
    String key;

    public Attributes() {}

    public Attributes(String s) {
        // Here, s is {"key":"value"} you can parse it into an Attributes
        // (this will use the no-arg constructor)
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Attributes a = objectMapper.readValue(s, Attributes.class);
            this.key = a.key;
        } catch(Exception e) {/*handle that*/}
    }

    // GETTERS/SETTERS  
}

然后您可以通过以下方式对其进行解析:

ObjectMapper objectMapper = new ObjectMapper();
MyDto myDto = objectMapper.readValue(json, MyDto.class);

这有点脏,但是您原来的JSON也很:)