3 回答
TA贡献2016条经验 获得超9个赞
谢谢您提供的三个杯子!
如果需要多个类型,则与泛型类型相同:
public class SingleElementToListDeserializer<T> implements JsonDeserializer<List<T>> {
private final Class<T> clazz;
public SingleElementToListDeserializer(Class<T> clazz) {
this.clazz = clazz;
}
public List<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
List<T> resultList = new ArrayList<>();
if (json.isJsonArray()) {
for (JsonElement e : json.getAsJsonArray()) {
resultList.add(context.<T>deserialize(e, clazz));
}
} else if (json.isJsonObject()) {
resultList.add(context.<T>deserialize(json, clazz));
} else {
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return resultList;
}
}
并配置Gson:
Type myOtherClassListType = new TypeToken<List<MyOtherClass>>() {}.getType();
SingleElementToListDeserializer<MyOtherClass> adapter = new SingleElementToListDeserializer<>(MyOtherClass.class);
Gson gson = new GsonBuilder()
.registerTypeAdapter(myOtherClassListType, adapter)
.create();
TA贡献1811条经验 获得超4个赞
建立三杯的答案,我有以下让JsonArray直接反序列化为数组的方法。
static public <T> T[] fromJsonAsArray(Gson gson, JsonElement json, Class<T> tClass, Class<T[]> tArrClass)
throws JsonParseException {
T[] arr;
if(json.isJsonObject()){
//noinspection unchecked
arr = (T[]) Array.newInstance(tClass, 1);
arr[0] = gson.fromJson(json, tClass);
}else if(json.isJsonArray()){
arr = gson.fromJson(json, tArrClass);
}else{
throw new RuntimeException("Unexpected JSON type: " + json.getClass());
}
return arr;
}
用法:
String response = ".......";
JsonParser p = new JsonParser();
JsonElement json = p.parse(response);
Gson gson = new Gson();
MyQuote[] quotes = GsonUtils.fromJsonAsArray(gson, json, MyQuote.class, MyQuote[].class);
- 3 回答
- 0 关注
- 772 浏览
添加回答
举报