0

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?

  • Please provide what you have already tried. – Yan Foto May 15 '19 at 10:27
  • Use any of the millions of libraries that exist online? GSON, JSON by Alibaba to name a few... – OcelotcR May 15 '19 at 10:28
  • Possible duplicate of [Converting JSON data to Java object](https://stackoverflow.com/questions/1688099/converting-json-data-to-java-object) – Izruo May 15 '19 at 12:31
  • Possible duplicate of [Array of JSON Object to Java POJO](https://stackoverflow.com/questions/55248523/array-of-json-object-to-java-pojo). Take a look on [Jackson](https://github.com/FasterXML/jackson-databind) and [gson](https://github.com/google/gson) libraries. – Michał Ziober May 15 '19 at 15:07

1 Answers1

1

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.

Izruo
  • 2,246
  • 1
  • 11
  • 23
Tayyab Razaq
  • 348
  • 2
  • 11