Storing JSON response in List, or HashMap

Viewed 408

I've got some JSON response from retrofit that I'm not sure how to deal it, could you help me with it? I just want to store it somewhere, but I think List wouldn't be good for it, so maybe HashMap? The response looks like

{ 
    "object" : 
    { 
        "key1" : "value1", 
        "key2" : "value2"
    }
}

and so on.. Could you give me any hint how should I store that? I would really appreciate any help.

2 Answers

A HashMap is the best way of storing it because it gives you access to special methods (such as containsKey, containsValue, and compute) which you can use to interpret and manipulate the data.

To avoid having to write boilerplate code, I'd recommend using a library to handle the parsing for you, such as Jackson. It will also help if you ever have to write your own JSON responses.

Assuming you want to parse the Json string to a structured format. You can use jackson to map it to a hashmap.

You can do it as following

import com.fasterxml.jackson.databind.ObjectMapper;

  public void foo() {
       String jsonString = " { \"object\" : { \"key1\" : \"value1\", \"key2\" : \"value2\" } } ";
        ObjectMapper mapper = new ObjectMapper();
        try {

            // convert JSON string to Map
            Map<String, String> map = mapper.readValue(jsonString, Map.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

You can get jackson from following dependency if you are using maven

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.8</version>
    </dependency>

You can read more at Jackson's Main Portal page

Related