枚举类型给我们的程序带来了好处,如何用Gson来实现与Json的互转呢?请看本文.
本文重点掌握如何自己写一个TypeAdapter及注册TypeAdapter和处理Enum类型.
实体类:
public enum PackageState {PLAY, UPDATE, UPDATING, DOWNLOAD, DOWNLOADING,}
public class PackageItem {
private String name;
private PackageState state;
private String size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PackageState getState() {
return state;
}
public void setState(PackageState state) {
this.state = state;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
@Override
public String toString() {
return "PackageItem [name=" + name + ", size=" + size + ", state="+ state + "]";
}
}
自己写一个转换器实现JsonSerializer<T>接口和jsonDeserializer<T>接口:
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class EnumSerializer implements JsonSerializer<PackageState>,JsonDeserializer<PackageState> {
// 对象转为Json时调用,实现JsonSerializer<PackageState>接口
@Override
public JsonElement serialize(PackageState state, Type arg1,JsonSerializationContext arg2) {
return new JsonPrimitive(state.ordinal());
}
// json转为对象时调用,实现JsonDeserializer<PackageState>接口
@Override
public PackageState deserialize(JsonElement json, Type typeOfT,JsonDeserializationContext context) throws JsonParseException {
if (json.getAsInt() < PackageState.values().length)
return PackageState.values()[json.getAsInt()];
return null;
}
}
测试类:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonTest6 {
public static void main(String[] args) {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(PackageState.class,new EnumSerializer());
Gson gson = gsonBuilder.create();
PackageItem item = new PackageItem();
item.setName("item_name");
item.setSize("500M");
item.setState(PackageState.UPDATING);// 这个 state是枚举值
String s = gson.toJson(item);
System.out.println(s);
System.out.println("--------------------------------");
PackageItem retItem = gson.fromJson(s, PackageItem.class);
System.out.println(retItem);
}
}
输出结果(结果中已经将state的对应枚举类型转为了int类型):
{"name":"item_name","state":2,"size":"500M"}--------------------------------PackageItem [name=item_name, size=500M, state=UPDATING]