1

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

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

上面的课很好。

然而:

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

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

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

4

1 回答 1

2

要让 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则将使用该值。

于 2019-11-14T11:42:11.283 回答