Akshay
Akshay

Reputation: 1817

Jackson converting dynamic json to map

I have a problem where some structure of the json is fixed while some part is dynamic. The end output has to be an object of type

Map<String,List<Map<String,String>>>

I am pasting a sample json code for which the jackson work -

    {
  "contentlets": [
    {
      "template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
      "modDate": "2017-01-06 13:13:20.0",
      "cachettl": "0",
      "title": "New Early Warnings",
      "subscribeToListIi": "[email protected]",
      "inode": "15bd497-1d8e-4bc7-b0f4-c799ed89fdc9",
      "privacySetting": "public",
      "__DOTNAME__": "New gTLD Early Warnings",
      "activityStatus": "Completed",
      "host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
      "languageId": 1,
      "createNotification": false,
      "folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
      "sortOrder": 0,
      "modUser": "dotcms.org.2897"
    }
  ]
}


ObjectMapper mapper = new  ObjectMapper();
Map<String,List<Map<String,String>>> myMap=mapper.readValue(responseStr.getBytes(), new TypeReference<HashMap<String,List<Map<String,String>>>>() {});

The above code is working fine but when the json changes to (basically a metadata tag is added) it is not able to convert to map.

{
  "contentlets": [
    {
      "template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
      "modDate": "2017-01-06 13:13:20.0",
      "cachettl": "0",
      "title": "New gTLD Early Warnings",
      "subscribeToListIi": "[email protected]",
      "inode": "15bd4057-1d8e-4bc7-b0f4-c799ed89fdc9",
      "metadata": {
        "author": "jack",
        "location": "LA"
      },
      "privacySetting": "public",
      "__DOTNAME__": "New gTLD Early Warnings",
      "activityStatus": "Completed",
      "host": "10b6f94a-7671-4e08-9f4b-27bca80702e7",
      "languageId": 1,
      "createNotification": false,
      "folder": "951ff45c-e844-40d4-904f-92b0d2cd0c3c",
      "sortOrder": 0,
      "modUser": "dotcms.org.2897"
    }
  ]
}    

Upvotes: 1

Views: 304

Answers (1)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

This is expected since the type of the value of metadata is not a String. If you change the type of the map accordingly then it works:

Map<String,List<Map<String,Object>>> myMap = mapper.readValue(reader, new TypeReference<HashMap<String,List<Map<String,Object>>>>() {});

Of course you are left with the problem that values in the map are not of the same type. so you need to ask yourself what is the desired data structure you want and how you further process it. However, one cannot deserialize a json structure into a simple String.

Upvotes: 2

Related Questions