问题描述
这似乎有点不寻常,但我正在寻找一种有效的方法将 JsonNode
转换/映射到 POJO
.
This may seem a little unusual, but I am looking for an efficient way to transform/map a JsonNode
into a POJO
.
我将我的一些模型信息存储在 json 文件中,并且我必须支持我的模型的几个版本.
I store some of my Model's information in json files and I have to support a couple of version of my model.
我所做的是将 json 文件加载到内存中的 JsonNode 中,应用几种版本控制策略以使其与我的模型的最新版本相匹配.
What I do is load the json file in memory in a JsonNode, apply a couple of versioning strategies to make it match the latest version of my Model.
ObjectMapper mapper = new ObjectMapper();
BufferedReader fileReader = new BufferedReader(new FileReader(projPath));
JsonNode rootNode = mapper.readTree(fileReader);
//Upgrade our file in memory
applyVersioningStrategy(rootNode);
ProjectModel project = mapJsonNodeToProject(rootNode);
除非有更快的方法,否则我最终可能会简单地手动将 JsonNodes
应用到我的模型
Unless there's a faster way to do it, I will probably end up simply manually applying the JsonNodes
to my Model
推荐答案
在 Jackson 2.4 中,您可以进行如下转换:
In Jackson 2.4, you can convert as follows:
MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);
其中 jsonObjectMapper
是 Jackson ObjectMapper
.
where jsonObjectMapper
is a Jackson ObjectMapper
.
在旧版本的 Jackson 中,它会是
In older versions of Jackson, it would be
MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);
这篇关于将 JsonNode 转换为 POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!