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;
    }
}

3 Answers 3

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)));
}
Sign up to request clarification or add additional context in comments.

Comments

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.

5 Comments

No, it is inherited from java.lang.Object and does not implement the list interface. Please, next time when you answer a question make sure that your answer is correct.
Then it is worth a try :)
Well, it doesn't throw an error but the List is still a list with JSONObjects. So didn't solve my problem.
I Understand, now converting JSONObject to user object is Challenging..!
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 ;

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.