我的课:
class ExampleBean { private String _firstField; private String _secondField; // respective getters and setters }
我希望看起来如下:
{ "FirstField":"value","SecondField":"value" }
而不是这样
{ "_FirstField":"value","_SecondField":"value" }
我按如下方式初始化解析器:
GsonBuilder builder = new GsonBuilder(); builder.setDateFormat(DateFormat.LONG); builder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE); builder.setPrettyPrinting(); set_defaultParser(builder.create());
我可以在“FieldNamePolicy”中看到API和documentation,但我很惊讶不能选择跳过“_”
我也知道我可以使用注释…
@ SerializedName (" custom_naming ")
…但是我不想为alllllll我的领域写这个……
对我来说区分局部变量和类的字段非常有用. :( 任何的想法?
编辑:会有很多明显的解决方案,(继承,gson覆盖方法,常规表达).我的问题更侧重于是否存在gson的原生解决方案或更少侵入性的修复?
也许我们可以建议新的FieldNamePolicy?
解决方法
GsonBuilder提供了一个方法setFieldNamingStrategy(),它允许您传递自己的FieldNamingStrategy实现.
请注意,这将取代对setFieldNamingPolicy()的调用 – 如果查看GsonBuilder的源,这两个方法是互斥的,因为它们设置了相同的内部字段(FieldNamingPolicy枚举是FieldNamingStrategy).
public class App { public static void main(String[] args) { Gson gson = new GsonBuilder() .setFieldNamingStrategy(new MyFieldNamingStrategy()) .setPrettyPrinting() .create(); System.out.println(gson.toJson(new ExampleBean())); } } class ExampleBean { private String _firstField = "first field value"; private String _secondField = "second field value"; // respective getters and setters } class MyFieldNamingStrategy implements FieldNamingStrategy { public String translateName(Field field) { String fieldName = FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(field); if (fieldName.startsWith("_")) { fieldName = fieldName.substring(1); } return fieldName; } }
输出:
{ "FirstField": "first field value","SecondField": "second field value" }