简体   繁体   English

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

[英]How parse nested escaped json with Jackson?

Consider json: 考虑json:

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

Should be parsed into classes: 应该解析为类:

public class MyDto {
    String name;
    Attributes myNestedJson;

}

public class Attributes {
    String key;
}

Can it be parsed without writing stream parser? 是否可以在不编写流解析器的情况下进行解析? (Note that myNestedJson contains json escaped json string) (请注意, myNestedJson包含json转义的json字符串)

I think you can add a constructor to Attributes that takes a String 我认为您可以向带String Attributes添加一个构造函数

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  
}

Then you can parse it this way: 然后您可以通过以下方式解析它:

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

This is a little dirty but your original JSON is too :) 这有点脏,但是您的原始JSON也太:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM