Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson parse string field as JSON

Tags:

java

jackson

I have the following JSON:

{
    "some_key": "{\"a\": 1, \"b\": \"text\"}"
}

As you can see some_key field is not a JSON object it is a string, that contains valid JSON.

I would like to parse it into following structure:

class Foo {
    Bar some_key;
}

class Bar {
    int a;
    String b;
}

UPDATE:

  • class A and B, has getters and setters, constructors. I haven't show them to keep sample short and simple.

  • I can't edit the weird structure of the JSON.

  • The question is how to ask Jackson parse the inner string field as JSON object.

like image 397
Rostyslav Roshak Avatar asked Mar 30 '17 12:03

Rostyslav Roshak


People also ask

How do you parse JSON strings into Jackson JsonNode model?

The process of parsing JsonString into JsonNode is very simple. We simply create an instance of ObjectMapper class and use its readTree() method in the following way: String str = "{\"proId\":\"001\",\"proName\":\"MX Pro 20\",\"price\":\"25k\"}"; ObjectMapper map = new ObjectMapper();

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

@t_liang is very close - just need a bit more room than a comment to show the working example...

With:

class Foo {
    @JsonDeserialize(using = BarDeserializer.class)
    private Bar some_key;
}

Then the current ObjectMapper is actually the JsonParser.getCodec():

public class BarDeserializer extends JsonDeserializer<Bar> {
    @Override
    public Bar deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        String text = p.getText();
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        return mapper.readValue(text, Bar.class);
    }
}

Then this...

ObjectMapper mapper = new ObjectMapper();

Foo foo = mapper.readValue(
        "{ \"some_key\": \"{\\\"a\\\": 1, \\\"b\\\": \\\"text\\\"}\" }",
        Foo.class);

System.out.println(foo.getSome_key());

... shows the expected value:

Bar [a=1, b=text]
like image 153
df778899 Avatar answered Oct 15 '22 11:10

df778899