Convert between wrapped JSON and flat structure pojo

I have a JSON structure that includes a wrapping layer that I do not have in my POJOs. For instance:

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, JSON has a category level (which for various reasons I don’t want to have in my Pojo).

I am looking for a way to use Jackson for serialization / deserialization to handle this smooth way.

I know that Jackson has a @JsonUnwrapped annotation that handles the opposite. I also know that there is a function request for the "@JsonWrapped" annotation, which I think will solve my case.

Thank you for any contribution or help with this, as I have looked around quite a bit. Any suggestions on how this can be achieved using any other library (e.g. gson, flexjson, etc.) are also interesting.

+4
source share
1 answer

You can try using this algorithm:

  • Read JSON as a Map .
  • Flatten map
  • Use ObjectMapper to convert Map to POJO.

An implementation might look 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)); 
+1
source

Source: https://habr.com/ru/post/1491584/


All Articles