如何解析嵌套与杰克逊逃脱JSON?

问题描述 投票:0回答:1

考虑JSON:

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

应该被解析成类:

public class MyDto {
    String name;
    Attributes myNestedJson;

}

public class Attributes {
    String key;
}

是否可以不用写流解析器解析? (请注意,myNestedJson包含JSON转义JSON字符串)

java json jackson2
1个回答
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是太:)

© www.soinside.com 2019 - 2024. All rights reserved.