Serializing list
理论上序列化集合应该与序列化其他对象时一致的,关键在于集合中的类型信息并没有包含在json序列中,因此在反序列化List时需要类型信息
Gson提供了TypeToken用来获得类型信息,这里尝试解释list中存放不同类型的实例失败,正确的方式是遍历json序列,参见
Gson使用方法之streaming
代码:
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
class Album {
public Album(String album_id, String album_title) {
this.album_id = album_id;
this.setAlbum_title(album_title);
}
public String getAlbumId() {
return album_id;
}
public String getAlbum_title() {
return album_title;
}
public void setAlbum_title(String album_title) {
this.album_title = album_title;
}
private String album_id;
private String album_title;
}
class AlbumOther {
public AlbumOther(int seq) {
this.album_seq = seq;
}
int album_seq;
}
public class ParseCollectionTest {
public static void main(String[] args) {
ArrayList<Object> datasets = new ArrayList<Object>();
datasets.add(new Album("1", "follow the river"));
datasets.add(new Album("2", "born with flower"));
//datasets.add(new AlbumOther(3)); //can not deal with different class
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
String json = gson.toJson(datasets);
System.out.println(json);
Type datasetType = new TypeToken<Collection<Album>>(){}.getType();
System.out.println(datasetType.toString());
ArrayList<Album> JsonToList = gson.fromJson(json, datasetType);
for (Album album : JsonToList) {
System.out.println(album.getAlbumId());
System.out.println(album.getAlbum_title());
}
}
}