How to convert a JsonNode instance to an actual pojo

旧城冷巷雨未停 提交于 2021-01-28 06:02:47

问题


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.


回答1:


In this case you can use two methods:

  • treeToValue
  • convertValue

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']


来源:https://stackoverflow.com/questions/60991716/how-to-convert-a-jsonnode-instance-to-an-actual-pojo

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