0

How can we convert the nested json to nested hashmap without creating the pojo classes.

{
  "IdeskFields": [
    {
      "fieldName": "CLIENT_TAX_TYPE_ID",
      "values": [
        {
          "key": "dataType",
          "value": "Integer"
        },
        {
          "key": "CLIENT_TAX_TYPE_VAT",
          "value": "2"
        },
        {
          "key": "CLIENT_TAX_TYPE_GST",
          "value": "8"
        },
        {
          "key": "CLIENT_TAX_TYPE_Tax",
          "value": "9"
        }
      ]
    }
  ]
}

Need to be converted to Map<String, Map<String, String>> map

1
  • You cannot directly convert the json string to Map<String, Map<String, String>>. If you observe, the root element is of type List. Then this list has specific object. This object internally has values of type Map. The the most apt solution would be to convert the json to Map<String, Object> Commented Apr 15, 2021 at 8:12

2 Answers 2

2

You can use ObjectMapper from jackson.

Map map = new ObjectMapper().readValue(jsonString, HashMap.class);

A map will be an instance of

HashMap<String, ArrayList<LinkedHashMap<String, ArrayList<LinkedHashMap<String, String>>>>>
Sign up to request clarification or add additional context in comments.

Comments

1

If you can use the Gson library then you can do something like this

Gson gson = new Gson();

Map map = gson.fromJson(str, Map.class);

But that would leave to the library to determine the type of values.

Therefore better way to use Gson#fromJson(String, Type) something like below:

Type mapType = new TypeToken<Map<String, List<Map<String, Object>>>>() {}.getType();

Map<String, List<Map<String, Object>>> map = gson.fromJson(str, mapType);

I use Object as inner map value type because your values are different i.e string and list of another map.

Comments

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.