Conversion between JSON with wrapped structure and pojo with flattended structure

不问归期 提交于 2021-01-27 07:30:47

问题


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...
}

As you can see, the JSON have a "category" level (that for different reasons I don't want to have in my Pojo).

I'm looking for a way to use Jackson for serializaion/deserialization to handle this in a smooth way.

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.

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.


回答1:


You can try with this algorithm:

  1. Read JSON as Map.
  2. Flatten map
  3. Use ObjectMapper to convert Map into 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));


来源:https://stackoverflow.com/questions/17670852/conversion-between-json-with-wrapped-structure-and-pojo-with-flattended-structur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!