如何将JsonNode实例转换为实际的Pojo [英] How to convert a JsonNode instance to an actual pojo
问题描述
在代码的特定位置,我已经将一个表示为字符串的JSON文档解析为 JsonNode
,因为我还不知道实际的目标pojo类类型.
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.
现在,一段时间后,我知道了pojo的 Class
实例,我想将此 JsonNode
转换为该类的实际pojo(用注释正确的 @JsonProperty
注释).能做到吗?如果可以,怎么办?
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?
我正在使用Jackson 2.10.x.
I am working with Jackson 2.10.x.
推荐答案
在这种情况下,您可以使用两种方法:
In this case you can use two methods:
请参见以下示例:
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
}
上面的 JSON
有效负载的代码如下:
Above code for JSON
payload like below:
{
"id": 1,
"body": "message body"
}
打印:
Message[id=1, body='message body']
Message[id=1, body='message body']
这篇关于如何将JsonNode实例转换为实际的Pojo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!