Home » Java » java – How to create POJO dynamically using JSON?-Exceptionshub

java – How to create POJO dynamically using JSON?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have multiple dyanamic json templates as belows

JSON 1

{
      "param1": "testuser1",
      "param2": "[email protected]"
}

JSON 2

{
      "param1": "testuser2",
      "param2": "[email protected]",
      "param3": "New York"
}

JSON 3

{
      "param1": "testuser3"
      "param2": "[email protected]",
      "param3": "New York",
      "param4": [
            {
                "sub-param1": "X",
                "sub-param2": "Y"
            },
            {
                "param1": "testuser",
                "param2": "[email protected]"
            }
          ]
}

I want to covert them into JAVA Object at runtime i.e. without creating POJO at compile time. Is this possible ? If yes how to do that?

I tried using Jackson lib to convert json into object (Object Class), but how to create common generic POJO or how to create POJO with setter getter dynamically?

How to&Answers:

You probably want to deserialize your JSON document into a Map<String, Object> or maybe use the Jackson tree model, as shown below:

TypeReference<Map<String, Object>> type = new TypeReference<Map<String, Object>>() {};
Map<String, Object> map = mapper.readValue(json, type);
JsonNode jsonNode = mapper.readTree(json);