public class KeyFieldNamingStrategy implements FieldNamingStrategy {
private final FieldNamingStrategy delegate;
public KeyFieldNamingStrategy(FieldNamingStrategy delegate) {
this.delegate = delegate;
}
@Override
public String translateName(Field f) {
Key key = f.getAnnotation(Key.class);
if (key == null) {
// No annotation, use delegate
return delegate.translateName(f);
} else {
return key.value();
}
}
}
然后将其注册到GsonBuilder:
Gson gson = new GsonBuilder()
// Uses IDENTITY as delegate, which uses field names as is
.setFieldNamingStrategy(new KeyFieldNamingStrategy(FieldNamingPolicy.IDENTITY))
.create();
1条答案
按热度按时间vsikbqxv1#
默认情况下,Gson只支持它的
@SerializedName
注解来指定自定义JSON成员名称。假设您正在使用的
@Key
注解在运行时可用(@Retention(RUNTIME)
),则可以编写一个自定义FieldNamingStrategy
:然后将其注册到
GsonBuilder
: