laaptu
laaptu

Reputation: 2973

Gson how to dynamically set serialized name

Here is my case

// a base class
public abstract class PageResult<T> {
   @SerializedName("success")
   public boolean success = false;
   @SerializedName("next_page")
   public int nextPage = -1;
   public ArrayList<T> dataList;
}

in dataList SerializedName need to be dynamic i.e.

public class StringPageResult extends PageResult<String>{
  //for this case 
  @SerializedName("StringResult")
  public ArrayList<String> dataList
}

public class IntegerPageResult extends PageResult<Integer>{
  //for this case 
  @SerializedName("IntegerResult")
  public ArrayList<Integer> dataList
}

So the class extending PageResult, SerializedName need to be different and all must use dataList. Meaning I need to use PageResult dataList for various processing instead of sub class dataList.Is it possible? I am doing it in following manner

public abstract class PageResult<T> {
  public abstract ArrayList<T> getDataList();
  @SerializedName("success")
  public boolean success = false;
  @SerializedName("next_page")
  public int nextPage = -1;
}

public class StringPageResult extends PageResult<String>{

  @SerializedName("StringResult")
  public ArrayList<String> dataList;
  public abstract ArrayList<String> getDataList(){
     return dataList;
  }
}

Upvotes: 2

Views: 3604

Answers (1)

SANAT
SANAT

Reputation: 9267

Use this :

@SerializedName(value="name1", alternate={"name2", "name3"})

https://google.github.io/gson/apidocs/com/google/gson/annotations/SerializedName.html

Upvotes: 3

Related Questions