简体   繁体   中英

How parse nested escaped json with Jackson?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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