Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson - Read a value with two different keys

Tags:

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

Response 1

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

Response 2

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

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

I don't want to create one more pojo for other response. My question is: is it 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...

like image 421
Bharatesh Avatar asked Mar 02 '16 06:03

Bharatesh


1 Answers

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

like image 72
Doug Stevenson Avatar answered Oct 02 '22 12:10

Doug Stevenson