Change attribute name dynamically Gson while Serialization

153 views
Skip to first unread message

Ranganath Panibhathe

unread,
Nov 2, 2018, 12:31:12 PM11/2/18
to google-gson

Hello All!


I've got MultivaluedMap of custom object types which I am serializing using Gson. One of my requirement is to change the name of one of the object based on the length of the string to some other name.


I know that we can use annotations @SerializedName but it provides option for only one name alternative whereas I'm looking for two names for the same attribute and use it dynamically when serializing based on the string length.


How can I accomplish this?


Here's the outline of my custom object types:

Toplevel Class:

public class CompleteData{

private String country,
private String appId,
Private String userId,

private List<RecipientInfo> recipients;
private CustomDocument document;

<<setters//getters>>
public CompleteData(String country, String appId, String userId, List<RecipientInfo> recipients, CustomDocument document){
this.country=country..
..
..
}

CustomDocument Class:

public class CustomDocument{
String name;
String pageCount;

public CustomDocument(String name, int pageCount){
this.name = name;
this.pageCount = pageCount;
}

RecipientInfo Class:

public class RecipientInfo{
@serializedName("fullName")
String name;
String phoneNum;

public RecipientInfo(String name, String phoneNum){
this.name = name;
this.phoneNum = phoneNum;
}
}

Now I create List<CompleteData> completeData = new ArrayList<>();


 Gather all the necessary information and add it to a MultivaluedMap as there are duplicate keys involved:

MultiValuedMap(<String, List<CompleteData>)

Now while using Gson to serialize this object, I want to change the "name" attribute in RecipientInfo class to be able to change dynamically based on the string length as fullname if the length is (>10 and <15) and fullNamewithSalu if the length is >20

Should I create a new class all together for this small change or is there a way I can serialize this object using Gson dynamically ?

Please help!


Thank you!

Reply all
Reply to author
Forward
0 new messages