Reputation: 2271
Gson gson = gsonBuilder.create();
String json = gson.toJson(obj);
This object contains a pair . When it is converted to json it's value is displayed as :
_first : 1.0 , _second : 2.0
i want to change the name of the variable first and second to some string.
Can I change the name of the fields using annotation on the object for example
class one {
@SerializedName("number")
int num ;
@Some annotation to change the name of field one and field two
Pair<Double,Double> var;
Pair<String,Integer> var2;
}
class Pair<T1,T2>{
T1 field_1;
T2 field_2;
}
Upvotes: 1
Views: 253
Reputation: 2271
I used a custom Serializer for solving this problem:
gsonBuilder.registerTypeAdapter(Pair.class, new PairCustomSerializer());
public class PairCustomSerializer implements JsonSerializer<Pair<?, ?>> {
@Override
public JsonElement serialize(Pair<?, ?> src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject obj = new JsonObject();
JsonArray arr = new JsonArray();
if (src.getFirst() instanceof Double) {
Double val1 = (Double) src.getFirst();
Double val2 = (Double) src.getSecond();
arr.add(val1);
arr.add(val2);
obj.add("value", arr);
return obj;
}
Upvotes: 1