将JsonNode转换为POJO

将JsonNode转换为POJO

本文介绍了将JsonNode转换为POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来有点不寻常,但我正在寻找一种有效的方法将 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 10:26