Java Google Json (Gson) Serializing Collections

Serializing list

Serializing Collections should have been similar to serializing other objects. However, the problem is that Collections are generic and the generic type information is not maintained in the json. We therefore pass the type while deserializing list. Note that if the Collection has different types of objects then there is no way to serialize it.

package com.studytrails.json.gson;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class DeSerializeListExample5 {
	public static void main(String[] args) {
		String json = "[{album_id:1,album_title:'album1'},{album_id:2,album_title:'album2'}]";

		Gson gson = new Gson();
		// create the type for the collection. In this case define that the collection is of type Dataset
		Type datasetListType = new TypeToken<Collection<Dataset>>() {}.getType();
		List<Dataset> datasets = gson.fromJson(json, datasetListType);
		for (Dataset dataset : datasets) {
			System.out.println(dataset.getAlbum_title());
			System.out.println(dataset.getAlbum_id());
		}
		// Prints
		//album1
		//1
		//album2
		//2
		
	}
}

The Dataset Class

package com.studytrails.json.gson;

import java.util.HashMap;
import java.util.Map;

public class Dataset {
	private String album_id;
	private String album_title;
	private Map<String , Object> otherProperties = new HashMap<String , Object>();

	public String getAlbum_id() {
		return album_id;
	}

	public void setAlbum_id(String album_id) {
		this.album_id = album_id;
	}

	public String getAlbum_title() {
		return album_title;
	}

	public void setAlbum_title(String album_title) {
		this.album_title = album_title;
	}

	public Object get(String name) {
		return otherProperties.get(name);
	}

}

Leave a Comment