使用gson反序列化json数组? [英] Deserializing json array using gson?
本文介绍了使用gson反序列化json数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{
status:200,
data :[
{
catId:638,
catName:Helena Bonham Carter,
catUniqueName:helena-bonham-carter,
catSlug:
},
{
...
}
]
}
我的分类模式为:
public class Category {
private double catId;
私人字符串catName;
私人字符串catUniqueName;
私人字符串catSlug;
}
我的gson自定义反序列化器如下所示:
类型listType = new TypeToken< ArrayList< Category>>(){}。getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(listType,new CategoryDeserializer())
.create();
$ b $ private class CategoryDeserializer实现JsonDeserializer {
@Override
public Category deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context)
throws JsonParseException {
Gson gson = new Gson();
return gson.fromJson(((JsonObject)json).get(data),typeOfT);
$ / code $ / pre
我使用Retrofit库,它使用gson来序列化/反序列化json对象。我通过这个自定义的gson解串器进行改进,但它给了我一个错误。你可以告诉我去序列化时出错的地方吗?
错误:
java.util.ArrayList不能转换为com.compzets.app.models.Category
预期结果:
我想要
来自json的Category
的ArrayList。类别更改deserialize()
的返回类型。到ArrayList< Category>
解决了这个问题。其余的代码是正确的。I have my json as:
{ "status": 200, "data": [ { "catId": 638, "catName": "Helena Bonham Carter", "catUniqueName": "helena-bonham-carter", "catSlug": "" }, { ... } ] }
My Category model as:
public class Category { private double catId; private String catName; private String catUniqueName; private String catSlug; }
And my gson custom deserializer is as follows:
Type listType = new TypeToken<ArrayList<Category>>(){}.getType(); Gson gson = new GsonBuilder() .registerTypeAdapter(listType, new CategoryDeserializer()) .create(); private class CategoryDeserializer implements JsonDeserializer { @Override public Category deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new Gson(); return gson.fromJson(((JsonObject) json).get("data"), typeOfT); } }
I am using Retrofit library which uses gson to serialize/deserialize json objects. I pass this custom gson deserializer to retrofit but it gives me an error. Can you tell me where I am going wrong while desrializing?
Error:
java.util.ArrayList cannot be cast to com.compzets.app.models.Category
Expected Result:
I want
ArrayList of Category
from json.解决方案Changing the return type of
deserialize()
fromCategory
toArrayList<Category>
solved the issue. Rest of the code is correct.这篇关于使用gson反序列化json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文