Karthik Cherukunnumal
Karthik Cherukunnumal

Reputation: 43

Convert a Json Array to Map in java

I am working on a project where I get a JSON response from my API using entities and DTO

Folowing is the response:

return XXXResponseDTO
                .builder()
                .codeTypeList(commonCodeDetailList)
                .build();

commonCodeDetailList list contains the data from the database. Final output will be

{
  "code_type_list": [
    {
      "code_type": "RECEIVING_LIST",
      "code_list": [
        {
          "code": "1",
          "code_name": "NAME"
        },
        {
          "code": "2",
          "code_name": "NAME1"
        }
      ],
      "display_pattern_list": [
        {
          "display_pattern_name": "0",
          "display_code_list": [
            "1",
            "2"
          ]
        }
      ]
    },
    {
      "code_type": "RECEIVING_LIST1",
      "code_list": [
        {
          "code": "1",
          "code_name": "NAME"
        }
      ],
      "display_pattern_list": [
        {
          "display_pattern_name": "0",
          "display_code_list": [
            "1"
          ]
        }
      ]
    }
  ]
}

I need to convert this to Map with key-value pairs. How could I achieve this?

Upvotes: 0

Views: 397

Answers (1)

Tayyab Razaq
Tayyab Razaq

Reputation: 378

Using Jackson, you can do the following:

ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(commonCodeDetailList);
Map<String, String> map = mapper.readValue(jsonStr, Map.class);

First you need to convert commonCodeDetailList into a json string. After that you can convert this json string to map.

Upvotes: 1

Related Questions