0

Is it possible using json-simple (and no other additional library) to convert a JSONArray to an ArrayList<MyObject>?

I was not able to find code samples in the documentation nor on SO.

This is how I do it at the moment (quite a bit complicated):

for(Iterator iterator = jsonRootObject.keySet().iterator(); iterator.hasNext();) {
    String key = (String) iterator.next();
    JSONObject jsonEpg = (JSONObject) jsonRootObject.get(key);
    JSONArray jsonEpgTags = (JSONArray) jsonEpg.get("tags");

    //Iterate tags
    for(int i = 0; i < jsonEpgTags.size(); i++) {
        JSONObject jsonEpgTag = (JSONObject) jsonEpgTags.get(i);
        final String tagId = (String) jsonEpgTag.get("id");
        String name = (String) jsonEpgTag.get("name");

        EpgJsonTagValue jsonTagValue = new EpgJsonTagValue();
        jsonTagValue.tagId = tagId;
        jsonTagValue.name = name;

        result.add(jsonTagValue);
    }
}

My "POJO":

public class EpgJsonTagValue {
    private String tagId;
    private String name;

    public String getTagId() {
        return tagId;
    }

    public void setTagId(String id) {
        this.tagId = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "TagId: " + tagId
                + ", Name: " + name;
    }
}
mosquito87
  • 4,270
  • 11
  • 46
  • 77

3 Answers3

1

You join the elements using a separator String, then split them to get an array, then pass this array to Arrays.asList which will be passed to the constructor of ArrayList.

public static ArrayList<Object> JSONArray2ArrayList(JSONArray input, Class c) {
    return new ArrayList<c>(Arrays.asList(input.join(separator).split(separator)));
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

You dont have to iterate JsonArray object to build a list. Its already implements List interface so just type cast it, like below

List<UserObject> result = (List<UserObject>) jsonArray;

Please try and let me know.

Thilak
  • 367
  • 2
  • 12
0

This will work for sure!!

List<EpgJsonTagValue> epgJsonTagValueList = (List<EpgJsonTagValue>)jsonEpgTags ;

Or if you want an ArrayList then this will work:

ArrayList<EpgJsonTagValue> epgJsonTagValueList = (ArrayList<EpgJsonTagValue>)jsonEpgTags ;
Shabbir Ahmad
  • 226
  • 2
  • 8