Gson - 使用两个不同的键读取值 [英] Gson - Read a value with two different keys

查看:230
本文介绍了Gson - 使用两个不同的键读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android项目中,我有两种类型的响应,其中响应相同,除了两个键

In my android project I have two types of response where both response are identical except two keys.

回复1

{"fullName":"William Sherlock Scott Holmes","address":"221B Baker Street, London, England, UK","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}

回复2

{"name":"Sherlock","city":"London","downloads":642,"rating":3,"repos":["https://link1","https://link2","https://link3"]}

如果您看到回复,则只有两个关键名称正在更改 fullName / name 地址/城市

If you see the responses only two key names are changing fullName/name and address/city

我不想为其他响应再创建一个pojo。现在我的问题是,是否可以只使用一个Pojo来读取这两个响应。

I don't want to create one more pojo for other response. Now my Question is, Is that possible to use only one Pojo to read both responses.

public class AccountInfo {
    private String name;
    private String city;
    //other objects

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
    //other setters and getters
}

任何帮助将不胜感激...

Any help will be appreciated...

推荐答案

您可以使用 @SerializedName 注释:

@SerializedName(value = "name", alternate = {"fullName"})
private String name;
@SerializedName(value = "city", alternate = {"address"})
private String city;

任何一个命名元素都可以放入这样注释的成员中。

Either named element can then be placed into the members that are annotated like this.

更新:
@SerializedName 版本2.4

UPDATED : @SerializedName alternate names when deserializing is added in Version 2.4

这篇关于Gson - 使用两个不同的键读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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