如何反序列化作为单个对象或带有GSON的对象列表传递的字段? [英] Howto deserialize field that is passed either as a single Object or as a list of Objects with GSON?
问题描述
我已成功使用GSON将JSON转换为单个Object并将JSON转换为对象列表。我的问题是有2个源向我发送数据。一个是发送一个对象,另一个是发送一个对象列表。
I have successfully used GSON to convert a JSON to a single Object and to convert JSON to a list of objects. My problem is that there are 2 sources emitting data to me. One is only sending one object and the other is sending a list of Objects.
单个对象来自第一个来源:
{
id : '1',
title: 'sample title',
....
}
来自第二来源的对象列表:
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
班级用于反序列化:
public class Post {
private String id;
private String title;
/* getters & setters */
}
以下是我的第一个案例:
Below is working for my 1st case:
Post postData = gson.fromJson(jsonObj.toString(), Post.class);
这适用于我的第二种情况:
And this is working for my 2nd case:
Post[] postDatas = gson.fromJson(jsonObj.toString(), Post[].class);
有没有办法管理这两种情况?或者我应该查看字符串并在不可用时添加[]
谢谢
Is there a way to manage both cases? Or should I look into the string and add [] when it is not available Thanks
推荐答案
如何创建一个自定义反序列化器,用于检查json是否为数组,如果没有,则创建一个包含单个对象的数组,如:
How about creating a custom deserializer that checks if the json is an array and if not creates an array having the single object in it, like:
public class PostArrayOrSingleDeserializer implements JsonDeserializer<Post[]> {
private static final Gson gson = new Gson();
public Post[] deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext ctx) {
try {
return gson.fromJson(json.getAsJsonArray(), typeOfT);
} catch (Exception e) {
return new Post[] { gson.fromJson(json, Post.class) };
}
}
}
并将其添加到您的Gson :
and adding it to your Gson:
Post[] postDatas = new GsonBuilder().setPrettyPrinting()
.registerTypeAdapter(Post[].class, new PostArrayOrSingleDeserializer())
.create()
.fromJson(jsonObj.toString(), Post[].class);
因此,您应始终拥有 Post $数组c $ c>包含一件或多件物品。
So as a result you should always have an array of Post
with on or more items.
这篇关于如何反序列化作为单个对象或带有GSON的对象列表传递的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!