How to convert a JsonNode instance to an actual pojo

Hazzo :

At a certain point in my code, I have parse a JSON document, represented as a string, to a JsonNode, because I don't know yet the actual target pojo class type.

Now, some time later, I know the Class instance of the pojo and I want to convert this JsonNode to an actual pojo of that class (which is annotated with the proper @JsonProperty annotations). Can this be done? If so, how?

I am working with Jackson 2.10.x.

Michał Ziober :

In this case you can use two methods:

See below example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.util.StringJoiner;

public class JsonNodeConvertApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(jsonFile);

        System.out.println(mapper.treeToValue(node, Message.class));
        System.out.println(mapper.convertValue(node, Message.class));
    }
}

class Message {
    private int id;
    private String body;

    // getters, setters, toString
}

Above code for JSON payload like below:

{
  "id": 1,
  "body": "message body"
}

prints:

Message[id=1, body='message body']
Message[id=1, body='message body']

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388968&siteId=1