Anuj
Anuj

Reputation: 51

How to convert my JSONObject into List of LinkedHashMap and eventually build a HashMap<Integer, customObject> using it?

JSONObject jsonObject = restTemplate().getForObject(endPointUrl , JSONObject.class)

jsonObject is like below

{"content":[{"id":12345,"code":"89879","Option1":"Raw","Option2":"Pure","Option3":"Mix","pborrow":true}, 
{"id":34234,"code":"89877","Option1":"Pure","Option2":"Raw","Option3":"Raw","pborrow":true},
{"id":8876,"code":"534554","Option1":"Raw","Option2":"Mix","Option3":"Mix","pborrow":true}
}]}

I want to convert this into List<LinkedHashMap> and later iterate over this List of LinkedHashMap and build a HashMap<Integer, CustomObject> where Key(Integer) will be code from each entry and CustomObject will be formed using values of Option1, Option2, and Option3

I tried like below to convert it into a List<LinkedHashMap> but this is giving exception -

List<Map> myJsonList = rootJsonObject.get("content") != null ? (List)  ((LinkedHashMap)rootJsonObject.get("content")) : null;

and once was successful my below code would create the responseMap HashMap<Integer, CustomObject>

HashMap<Integer, CustomObject> responseMap = new HashMap<Interger, CustomObject>();
Iterator it = myJsonList.iterator();

while (it.hasNext() {
    LinkedHashMap objectMap = (LinkedHashMap) it.next();
    String option1Value = objectMap.get("Option1").toString();
    String option2Value = objectMap.get("Option2").toString();
    String option3Value = objectMap.get("Option3").toString();
    Integer code = Integer.ParseInt(objectMap.get("code").toString())

    responseMap.put(code, new CustomObject(code, option1Value, option2Value, option3Value))
}

But the first part

List<Map> myJsonList = rootJsonObject.get("content") != null ? (List)  ((LinkedHashMap)rootJsonObject.get("content")) : null;

itself is failing... someone can help to build the List<LinkedHashMap> out of jsonObject?

Please note the JSON contains many fields and I am interested in only 4 fields to build the custom object.

Upvotes: 0

Views: 374

Answers (1)

Arkady Dymkov
Arkady Dymkov

Reputation: 43

I suggest you to do it through object. It will be more clean. Create content class:

public class Content{

    public int id;

    public String code;

    @JsonProperty("Option1") 
    public String option1;

    @JsonProperty("Option2") 
    public String option2;

    @JsonProperty("Option3") 
    public String option3;
    
    public boolean pborrow;
}

and Root class:

public class Root{
    public ArrayList<Content> content;
}

Import any json package u like and use it:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
ObjectMapper om = new ObjectMapper();
Root root = om.readValue(myJsonString, Root.class);

or just:

List<Content> contentList;
om.readValue(myJsonString, contentList.class);

then you can create ur map.

Upvotes: 1

Related Questions