Skip to content Skip to sidebar Skip to footer

Deserializing A Json Object With Multiple Items Inside It

I'm trying to deserialize (using gson) a JSON object that looks like this: 'attachments': { '40': { 'ID': 40, 'URL': 'http:\/\/

Solution 1:

This is an example of data that probably should have been serialized as an array, but was not. One solution to parsing it is to utilize a JSONObject directly.

String json = ...;
final Gson gson = new Gson();

finalList<Attachment> attachements = new ArrayList<Attachment>(64);
final JSONObject jsonObj = new JSONObject(json).getJSONObject("attachments");
finalIterator<String> keys = jsonObj.keys();
while(keys.hasNext()) {
    finalString key = keys.next();
    attachements.add(gson.fromJson(jsonObj.getJSONObject(key).toString(), Attachment.class);
}

// Do something with attachements

The data can also be viewed as a map, of id's to attachments. And it can be deserialized as such:

final String jsonObj = newJSONObject(json).getJSONObject("attachments");
final Gson gson = newGson();
final Map<String, Attachment> data = gson.fromJson(jsonObj.toString(),
        newTypeToken<Map<String, Attachment>>() {
        }.getType());
final List<Attachment> attachments = newArrayList<Attachment>(data.values());

This is actuall

Solution 2:

First create JSONArray from this JSONObject., then

for(inti=0; i < contacts.length(); i++){
            JSONObjectc= contacts.getJSONObject(i);

By using this loop get the string values and put in a map or object that u want and add it to a ArrayList

HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, id);

And

contactList.add(map);

then you can use that values.

Solution 3:

How do I handle it? I don't even know what to call this - There are multiple "items" represented here, but it's not an array.

It looks like the collection in the JSON is a natural fit for a java.util.map. So, I'd probably deserialize the JSON "attachments" into a Map<String, Atachment>. The map is then easy to iterate over, or transform the collection of Attachment values into a different type of collection, like a List<Attachment> or an Attachment[].

Note: The Gson User Guide includes an example of deserializing into a Generic Collection.

Post a Comment for "Deserializing A Json Object With Multiple Items Inside It"