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?

4
  • Please provide what you have already tried. Commented May 15, 2019 at 10:27
  • Use any of the millions of libraries that exist online? GSON, JSON by Alibaba to name a few... Commented May 15, 2019 at 10:28
  • Possible duplicate of Converting JSON data to Java object Commented May 15, 2019 at 12:31
  • Possible duplicate of Array of JSON Object to Java POJO. Take a look on Jackson and gson libraries. Commented May 15, 2019 at 15:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

What is ObjectMapper? Or in other words: What library are you using?
ObjectMapper is part of the Jackson Project
@Vringar I know and I'm asking, because this should be part of the answer.
In this case I am confused why you didn't just go ahead and edit the answer.
@Vringar Because I don't have enough reputation to bypass peer review, which quite too often stops me from queuing edits. I did edit now, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.