杰克逊将动态json转换为地图

时间:2017-01-16 15:29:01

标签: java json jackson

我有一个问题,其中json的某些结构是固定的,而某些部分是动态的。结束输出必须是

类型的对象
Map<String,List<Map<String,String>>>

我正在粘贴杰克逊工作的示例json代码 -

    {
  "contentlets": [
    {
      "template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
      "modDate": "2017-01-06 13:13:20.0",
      "cachettl": "0",
      "title": "New Early Warnings",
      "subscribeToListIi": "am@zz.com",
      "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>>>>() {});

上面的代码工作正常但是当json更改为(基本上添加了元数据标记)时,它无法转换为map。

{
  "contentlets": [
    {
      "template": "8f8fab8e-0955-49e1-a2ed-ff45e3296aa8",
      "modDate": "2017-01-06 13:13:20.0",
      "cachettl": "0",
      "title": "New gTLD Early Warnings",
      "subscribeToListIi": "aml@bb.com",
      "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"
    }
  ]
}    

1 个答案:

答案 0 :(得分:2)

这是预期的,因为元数据的值的类型不是String。如果您相应地更改了地图的类型,那么它可以工作:

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

当然,你留下的问题是地图中的值不是同一类型。所以你需要问问自己,你想要的数据结构是什么,以及你如何进一步处理它。但是,不能将json结构反序列化为简单的String