如何替换SerializedName

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

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

上面的课很好。

但是:

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

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

如何使Gson识别MyAnnotation#value()并将其处理为SerializedName#value()

fanqi789 回答:如何替换SerializedName

要使Gson识别自制注释,请实施自定义this.mydata = data.json();

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值。

本文链接:https://www.f2er.com/3103149.html

大家都在问