隨着Gson
新版本,你可以創建自定義TypeAdapterFactory的List
性能。我實施了簡單的UnmodifiableListTypeAdapter
,但我不確定一切正常。請閱讀文檔,瞭解如何正確實施它。
class ListTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
Type type = typeToken.getType();
if (typeToken.getRawType() != List.class || !(type instanceof ParameterizedType)) {
return null;
}
Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
return new UnmodifiableListTypeAdapter(elementAdapter);
}
}
class UnmodifiableListTypeAdapter<E> extends TypeAdapter<List<E>> {
private TypeAdapter<E> elementAdapter;
public UnmodifiableListTypeAdapter(TypeAdapter<E> elementAdapter) {
this.elementAdapter = elementAdapter;
}
@Override
public List<E> read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
List<E> list = new ArrayList<E>();
reader.beginArray();
while (reader.hasNext()) {
E element = elementAdapter.read(reader);
list.add(element);
}
reader.endArray();
return Collections.unmodifiableList(list);
}
@Override
public void write(JsonWriter writer, List<E> list) throws IOException {
if (list == null) {
writer.nullValue();
return;
}
writer.beginArray();
for (E item : list) {
elementAdapter.write(writer, item);
}
writer.endArray();
}
}
用法示例可能看起來像這樣:
public class GsonProgram {
public static void main(String[] args) throws Exception {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapterFactory(new ListTypeAdapterFactory());
Gson gson = gsonBuilder.create();
System.out.println(gson.fromJson("{strings:[\"firstString\"],integers:[23,34,56]}",
Entity.class));
}
}
class Entity {
private List<String> strings;
private List<Integer> integers;
public List<String> getStrings() {
return strings;
}
public void setStrings(List<String> strings) {
this.strings = strings;
}
public List<Integer> getIntegers() {
return integers;
}
public void setIntegers(List<Integer> integers) {
this.integers = integers;
}
@Override
public String toString() {
return "Entity [strings=" + strings + ", integers=" + integers + "]";
}
}
上面的程序打印:
Entity [strings=[firstString], integers=[23, 34, 56]]
「mylist」字段的類型在哪裏? – PomPom