GSON java 我如何在映射和打印之间使用不同的名称?

Ani*_*vid 5 java android json gson

我有一个像这样的 JSON:

{
  "aggregation": {
    "CityAgg" : {
      "key" : "Paris"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我创建映射,并为每个字段添加 a ,@SerializedName因为我想为变量创建自定义名称。

例如,在 JSON 中,有一个键名称key,但我希望 Java 中的变量是cityName

所以,我这样做:

@SerializedName("key")
public String cityName
Run Code Online (Sandbox Code Playgroud)

我可以将响应 JSON 动态映射到我的对象,如下所示:

Gson gson = new Gson();
Query2 query2 = gson.fromJson(response, Query2.class);
Run Code Online (Sandbox Code Playgroud)

它工作得很好。

但是,当我想打印映射的对象时,我会这样做:

String query2String = gson.toJson(query2);
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gsonPretty.toJson(query2String);
Run Code Online (Sandbox Code Playgroud)

问题是,在 中prettyJson,我可以看到key,而不是cityName

我想知道是否有办法定制它。我不想看到key

Vis*_*nan 0

您应该使用自定义反序列化器,或者您应该使用反射更改注释的值。

更新:最差的解决方案

使用反射看起来像这样

    ClassLoader classLoader = URLClassLoader.newInstance(new URL[]{YourClass.class.getResource("YourClass.class")});
    Class locAnnotation = classLoader.loadClass("yourPackage.Query2");

    Field field = locAnnotation.getDeclaredField("cityName");
    final Annotation fieldAnnotation = field.getAnnotation(SerializedName.class);
    changeAnnotationValue(fieldAnnotation, "oldValue", "newValue");


public static Object changeAnnotationValue(Annotation annotation, String key, Object newValue) {
    Object handler = Proxy.getInvocationHandler(annotation);
    Field f;
    try {
        f = handler.getClass().getDeclaredField("memberValues");
    } catch (NoSuchFieldException | SecurityException e) {
        throw new IllegalStateException(e);
    }
    f.setAccessible(true);
    Map<String, Object> memberValues;
    try {
        memberValues = (Map<String, Object>) f.get(handler);
    } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new IllegalStateException(e);
    }
    Object oldValue = memberValues.get(key);
    if (oldValue == null || oldValue.getClass() != newValue.getClass()) {
        throw new IllegalArgumentException();
    }
    memberValues.put(key, newValue);
    return oldValue;
}
Run Code Online (Sandbox Code Playgroud)