Home > Software engineering >  how to convert json to list/map with jackson
how to convert json to list/map with jackson

Time:11-26

I encountered a piece of json as below:

{
  "code": 1,
  "msg": "query success",
  "obj": {
    "data": [
      {
        "name": "",
        "value": {
          "num": "89"
        }
      },
      {
        "name": "1",
        "value": {
          "num": "19"
        }
      },
      {
        "name": "2",
        "value": {
          "num": "6"
        }
      }
    ]
  },
  "success": true,
  "duration": 523
}

I need name and num. How to convert it to a list of java.util.List<HashMap<String, String>> with Jackson?

CodePudding user response:

You can use Jackson ObjectMapper with TypeReference , First you need to read it as Map<String,Object> then you can extract the name and num with Java.

you need to get the data from obj then for each item in the dataList you have to map it to a new HashMap as shown below

ObjectMapper objectMapper = new ObjectMapper ();
Map<String,Object> jsonMap = objectMapper.readValue(jsonData,new TypeReference<Map<String,Object>>(){});
List<Object> data = ((Map<String,Object>)jsonMap.get("obj")).get("data");
List<Map<String,String> result = data.stream()
   .map(d->(Map<String,Object> d)
   .map(d->{
      Map<String,String> map = new HashMap();
      map.put(d.get("name"),((Map<String,String>)d.get("value")).get("num"));
      return map;
      })
   .collect(Collectors.toList());

However if you can create a class for the the data it will be bit easier.

  • Related