Gson解析具有不同数据的相同密钥 [英] Gson Parsing same key with different data

查看:48
本文介绍了Gson解析具有不同数据的相同密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何解析服务器接收的包含不同密钥值的数据?

How could I parse data received by server that contains different values for a key ?

{ "location":[{"id":"1"},{"id":"2"}]}

{"location":{"id":"1"}}

不确定如何处理以下对象:

Do not know for sure how to handle the following object :

   public class UserLocation {
    @SerializedName("location")
    List<String> location; / String location;

   @SerializedName("name")
    String name;
}

在第一个请求中,我确实获取了数组格式,在第二个请求中,我确实从服务器获取了字符串格式.

In a first request, I do get the array format and in a second request I do get string format from the server.

推荐答案

您必须为此使用自定义反序列化:

you have to use custom deserialization for that like this:

JsonDeserializer<UserLocation> deserializer = new JsonDeserializer<UserLocation>() {
                @Override
                public UserLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                    List<String> location  = new ArrayList<>();
                    if(json.isJsonArray()){
                        JsonArray jsonArray = json.getAsJsonArray();

                        for (JsonElement jsonElement : jsonArray) {
                            location.add(jsonElement.getAsString());
                        }

                    }else{
                        location.add(json.getAsString());
                    }
                    return  new UserLocation(location);
                }
            };

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(UserLocation.class, deserializer);
Gson customGson = gsonBuilder.create();
UserLocation object = customGson.fromJson(jsoninput, UserLocation.class);

检查此链接以获得更多详细信息

check this link for more details

这篇关于Gson解析具有不同数据的相同密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆