【问题标题】:How to Replace SerializedName如何替换序列化名称
【发布时间】:2019-11-14 11:12:08
【问题描述】:

假设我想要的 JSON 是 {"grrrr":"zzzzz"}

class MyClass{
    @SerializedName("grrrr")
    private String myString;
}

上面的课没问题。

但是:

class MyClass{
    @MyAnnotation("grrrr")
    private String myString;
}

这将产生{"myString":"zzzzz"}

如何让Gson识别MyAnnotation#value()并处理为SerializedName#value()

【问题讨论】:

  • 这不是我所需要的。我已经更新了问题,请再看一下,谢谢。
  • 用例是什么?我的意思是,你为什么不能直接使用@SerializedName
  • 为了让 Gson 识别自制的注解,实现一个自定义的FieldNamingStrategy

标签: java gson


【解决方案1】:

要让 Gson 识别自制注解,请实现自定义 FieldNamingStrategy

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
    String value();
}
class MyNamingStrategy implements FieldNamingStrategy {
    @Override
    public String translateName(Field f) {
        MyAnnotation annotation = f.getAnnotation(MyAnnotation.class);
        if (annotation != null)
            return annotation.value();
        // Use a built-in policy when annotation is missing, e.g.
        return FieldNamingPolicy.IDENTITY.translateName(f);
    }
}

然后在创建 Gson 对象时指定它。

Gson gson = new GsonBuilder()
        .setFieldNamingStrategy(new MyNamingStrategy())
        .create();

并像在问题中一样使用它。

class MyClass{
    @MyAnnotation("grrrr")
    private String myString;
}

请注意@SerializedName 会覆盖任何已定义的策略,因此如果您同时指定@SerializedName@MyAnnotation,则将使用@SerializedName 值。

【讨论】:

  • 你是个巫师 =) +1
猜你喜欢
  • 2022-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多