【问题标题】:How parse nested escaped json with Jackson?如何用 Jackson 解析嵌套的转义 json?
【发布时间】:2019-02-05 09:39:39
【问题描述】:

考虑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】:

    我认为您可以向 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 太脏了 :)

    【讨论】:

    • 我认为 new ObjectMapper() 对于每个 dto 构造函数调用都无效。
    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2015-09-12
    • 1970-01-01
    相关资源
    最近更新 更多