具有包装结构的JSON和具有扁平结构的pojo之间的转换 [英] Conversion between JSON with wrapped structure and pojo with flattended structure
问题描述
我有一个JSON结构,其中包含了我的POJO中没有的包装级别.像这样:
I have a JSON structure that incorporates a wrapping level that I don't have in my POJOs. Like so:
JSON:
{
"category1": {
"cat1Prop1": "c1p1",
"cat1Prop2": "c1p2",
"cat1Prop3": "c1p3"
},
"category2": {
"cat2Prop1": "c2p1",
"cat2Prop2": "c2p2"
},
"category3": {
"cat3Prop1": "c3p1",
"cat3Prop2": "c3p2",
"cat3Prop3": "c3p3"
},
"category4": {
"cat4Prop1": "c4p1"
}
}
POJO:
public class MyPojo {
private String cat1Prop1;
private String cat1Prop2;
private String cat1Prop3;
private String cat2Prop1;
private String cat2Prop2;
private String cat3Prop1;
private String cat3Prop2;
private String cat3Prop3;
private String cat4Prop1;
// Getters / setters, etc...
}
如您所见,JSON具有类别"级别(出于各种原因,我不想在Pojo中使用它).
As you can see, the JSON have a "category" level (that for different reasons I don't want to have in my Pojo).
我正在寻找一种使用Jackson进行序列化/反序列化的方法,以便以一种流畅的方式进行处理.
I'm looking for a way to use Jackson for serializaion/deserialization to handle this in a smooth way.
我知道Jackson的 @ JsonUnwrapped 注释则相反.我还知道,有一个功能请求,它要求"@JsonWrapped" 批注我认为这可以解决我的问题.
I'm aware that Jackson has a @JsonUnwrapped annotation that kind of handles the opposite. I'm also aware that there is a feature request for a "@JsonWrapped" annotation that I think would solve my case.
非常感谢您提供的任何输入或帮助,因为我一直在四处寻找.另外,关于如何使用其他任何库(例如gson,flexjson等)完成此操作的任何建议也很有趣.
Thankful for any input or help regarding this, as I have been looking around quite a bit. Also, any suggestions on how this could be accomplished using any other library (like gson, flexjson, etc) is also interesting.
推荐答案
您可以尝试使用以下算法:
You can try with this algorithm:
- 将JSON读取为
Map
. - 平面地图
- 使用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));
这篇关于具有包装结构的JSON和具有扁平结构的pojo之间的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!