Search code examples
javajsonjacksonobjectmapper

Map dynamic JSON data to pojo class in Java?


I am creating a crud form in which I am producing and consuming Json data.

Problem: Json data I am producing is very dynamic. So I don't know how to map it to my pojo class.

What I have tried

1) Using jackson library, I created structure of my json data and 
tried mapping with it. It failed as in data "**Keys**" are dynamic so mapping failed.
2) I searched and found JsonNode provided by Jackson, problem with 
this is my json structure has key:[{},{}] structure like this 
**key-->array of objects**, so I tried parsing it with json node but failed.

My Json Data

Type 1

{
  "city_master": [
    {
      "citycode": [
        "100",
        "1130385"
      ]
    },
    {
      "cityname": [
        "London",
        "1130383"
      ]
    },
    {
      "statecode": [
        "512",
        "1130382"
      ]
    }
  ]
}

Problem with structure is that key = "city_master" or any key in this format eg("citycode", "cityname" etc) is dynamic so can't create mapping pojo for this class.

Then I tried fixing the outer key as root and parse is as Json Node as

Type 2

{
  "root": [
    {
      "citycode": [
        "100",
        "1130385"
      ]
    },
    {
      "cityname": [
        "London",
        "1130383"
      ]
    },
    {
      "statecode": [
        "512",
        "1130382"
      ]
    }
  ]
}

In this structure I loose my key value, but I can store it else where.

With JsonNode (Type-2) I tried this

String jsonString = tdObj.getTempData(); // return's Json String
TempDataTblPojo obj = new ObjectMapper().readValue(jsonString, TempDataTblPojo.class);
JsonNode jsonNode = obj.getRoot();
System.out.println("Name = " + jsonNode);

This class TempDataTblPojo

public class TempDataTblPojo {

    private JsonNode  root;

    public JsonNode getRoot() {
        return root;
    }

    public void setRoot(JsonNode root) {
        this.root = root;
    }
}

It prints this

Name = [{"citycode":["100","1130385"]},{"cityname":["London","1130383"]},{"statecode":["512","1130382"]}]

Now how to parse this JsonNode, to get all this key-value's? Or is there is efficient or much more cleaner solution, I will be happy to accept.


Solution

  • Maybe this will help you.

    class Pojo {
    
        private List<PojoItem> root;
    
        public List<PojoItem> getRoot() {
            return root;
        }
    
        public void setRoot(List<PojoItem> root) {
            this.root = root;
        }
    }
    
    class PojoItem {
    
        private Map<String, List<String>> items = new HashMap<>();
    
        public Map<String, List<String>> getItems() {
            return items;
        }
    
        @JsonAnySetter
        public void setItem(String key, List<String> values) {
            this.items.put(key, values);
        }
    }
    

    And then you can get it from json using this:

    Pojo result = objectMapper.readValue(json, Pojo.class);