Search code examples
javajsonjakarta-eejacksonobjectmapper

Jackson to convert a json into a map of String and a list


I have a json like below

{
  "department": [
    {
      "status": "active",
      "count": "100"
    },
    {
      "status": "active",
      "count": "300"
    }
  ],
  "finance": [
    {
      "status": "inactive",
      "count": "500"
    },
    {
      "status": "active",
      "count": "450"
    }
  ]
}

My Object is like below

class CurrentInfo
{
private String status;
private int count;
//getters and setters
}

I wanted to convert this JSON to a Map<String,List<CurrentInfo>>. I can convert the individual nodes using the below

ObjectMapper mapper = new ObjectMapper();
CurrentInfo currentinfo = mapper.readValue(jsonString, CurrentInfo.class);

Is there a way I can convert the previously mentioned JSON directly into a Map<String,List<CurrentInfo>>


Solution

  • Yes you can, and according to JSON above count is String type not int

    class CurrentInfo {
        private String status;
        private String count;
        //getters and setters
    }
    

    The use TypeReference to convert json string to java object

    Map<String, List<CurrentInfo>> currentInfo = mapper.readValue(
            jsonString,
            new TypeReference<Map<String, List<CurrentInfo>>>() {});