是否可以通过注释 class 的对象而不是注释字段来更改 class 的字段的 json 名称
is it possible to Change the json name of fields of a class by annotating the object of the class instead of annotating the fields
Gson gson = gsonBuilder.create();
String json = gson.toJson(obj);
此对象包含一对 。当它转换为 json 时,它的值显示为:
_first : 1.0 ,
_second : 2.0
我想将变量 first 和 second 的名称更改为某个字符串。
我可以使用对象上的注释更改字段的名称吗
例如
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;
}
我使用自定义序列化器来解决这个问题:
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;
}
Gson gson = gsonBuilder.create();
String json = gson.toJson(obj);
此对象包含一对 。当它转换为 json 时,它的值显示为:
_first : 1.0 , _second : 2.0
我想将变量 first 和 second 的名称更改为某个字符串。
我可以使用对象上的注释更改字段的名称吗 例如
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;
}
我使用自定义序列化器来解决这个问题:
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;
}