0

I have this structure of my JSON response string:

{
    "1":{
        "data1":"1","data2":"test1", ...
    },
    "2":{
        "data1":"6","data2":"test2", ...
    },
    ...
}

And I want to get the values to put into an ArrayList<MyItem>. I use GSON and normally I can do it in this way:

ArrayList<MyItem> items = 
    gson.fromJson(jsonString, new TypeToken<ArrayList<MyItem>>() {}.getType());

The problem is, that it does not work, because my JSON String has numbers as keys, but I only want to get the values to put into the ArrayList (unfortunately, the JSON string can not be changed by myself). How can I do this efficiently?

1
  • 1
    Why not try to put the json into Map<Integer, ArrayList<MyItem>> map and afterwards List<MyItems> map = foreach(..)? Commented Mar 6, 2013 at 19:55

2 Answers 2

1

I'd probably deserialize the JSON into a java.util.Map, get the values from the Map as a Collection using the Map.values() method, and then create a new ArrayList using the constructor that takes a Collection.

Sign up to request clarification or add additional context in comments.

1 Comment

I did it this way. I thought, there is a better solution, but I also did not find one.
0

Write a custom deserializer.

class MyItem 
{
    String data1;
    String data2;
    // ...
}

class MyJSONList extends ArrayList<MyItem> {}

class MyDeserializer implements JsonDeserializer<MyJSONList> 
{
    public MyJSONList deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) 
        throws JsonParseException
    {
        MyJSONList list = new MyJSONList();
        for (Entry<String, JsonElement> e : je.getAsJsonObject().entrySet())
        {
            list.add((MyItem)jdc.deserialize(e.getValue(), MyItem.class));
        }

        return list;
    }

}

Example:

String json = "{\"1\":{\"data1\":\"1\",\"data2\":\"test1\"},\"2\":{\"data1\":\"6\",\"data2\":\"test2\"}}";
Gson g = new GsonBuilder()
            .registerTypeAdapter(MyJSONList.class, new MyDeserializer())
            .create();
MyJSONList l = g.fromJson(json, MyJSONList.class);


for (MyItem i : l)
{
    System.out.println(i.data2);
}

Output:

test1
test2

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.