How parse nested escaped json with Jackson?

不想你离开。 提交于 2021-01-29 08:00:23

问题


Consider 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)


回答1:


I think you can add a constructor to Attributes that takes a 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  
}

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 :)



来源:https://stackoverflow.com/questions/54531391/how-parse-nested-escaped-json-with-jackson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!