简体   繁体   中英

Convert raw json string in json object with Jackson

Json objects can have strings, and those strings can represent another Json object. Ex:

{
  "foo" : "foo",
  "bar" : "{\"fizz\":\"baz\"}"
}

Above JSON as Java String:

"{ \"foo\" : \"foo\", \"bar\" : \"{\\\"fizz\\\":\\\"baz\\\"}\"}"

Assuming the above structure, how do I make jackson deserialize the bar property as a another POJO? Example?

class FooBar{
    private String foo;
    private FizzBazz bar;
}

class FizzBazz {
    private String fizz;
}

Use ObjectMapper from com.fasterxml.jackson.core jackson-databind

public void convertToPojo(){
String jsonInString="{ \"foo\" : \"foo\", \"bar\" : \"{\\\"fizz\\\":\\\"baz\\\"}\"}";

ObjectMapper mapper = new ObjectMapper();
FooBarclsObject = mapper.readValue(jsonInString, FooBar.class);
}

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