Gson - Read a value with two different keys

◇◆丶佛笑我妖孽 提交于 2019-12-04 22:26:50
Doug Stevenson

You can annotate the members to accept values from two different json names using the @SerializedName annotation:

@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.

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

Yes, you can totally use one POJO class for deserializing both responses. Your POJO class will contain keys from both responses.

public class Response {


private String name;
private String city;
private String fullName;
private String address;
private Integer downloads;
private Integer rating;
private List<String> repos ;

}

But when using the Response class, be careful that for first response, the name and city will be null, and for the second one, the address and fullname.

Yeah you can do that in a single POJO. Try this:

public class POJO {

@SerializedName("name")
public String name;

@SerializedName("city")
public String city;

@SerializedName("fullName")
public String fullName;

@SerializedName("address")
public String address;

@SerializedName("downloads")
public Integer downloads;

@SerializedName("rating")
public Integer rating;

@SerializedName("repos")
public List<String> repos = new ArrayList<String>();

}

While parsing you have to check values for null. For eg -

While Parsing Response 1: name and city variables will be null

While Parsing Response 2: fullname and address will be null

Note : Try checking values for null before using else you'll get nullpointerexception

Define all possible fields in your POJO Class like

    public class AccountInfo {
      private String name;
      private String city;
      private String fullname;
      private String address;
    }

While performing operation check for null in those feilds

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!