且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有包装结构的JSON和具有扁平结构的pojo之间的转换

更新时间:2021-10-22 22:42:16

您可以尝试使用以下算法:

You can try with this algorithm:

  1. 将JSON读取为Map.
  2. 平面地图
  3. 使用ObjectMapper将Map转换为POJO.

实施可能看起来像这样:

Implementation could looks like this:

ObjectMapper mapper = new ObjectMapper();

Map<String, Map<String, String>> map = mapper.readValue(new File("X:/test.json"), Map.class);
Map<String, String> result = new HashMap<String, String>();
for (Entry<String, Map<String, String>> entry : map.entrySet()) {
    result.putAll(entry.getValue());
}

System.out.println(mapper.convertValue(result, MyPojo.class));