我的类:
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());
我可以在API和"FieldNamePolicy"的文档中看到,但我很惊讶没有给出跳过"_"的选项我也知道我可以使用注释。。。
@ SerializedName (" custom_naming ")
但我不想为我所有的领域写这个。。。
区分局部变量和类的字段对我来说非常有用(有什么想法吗?
EDIT:会有许多明显的解决方案(继承、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"
}
您想要的是
import java.lang.reflect.Field;
import java.text.DateFormat;
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonExample {
public static void main(String... args) throws Exception {
final GsonBuilder builder = new GsonBuilder();
builder.setDateFormat(DateFormat.LONG);
builder.setPrettyPrinting();
builder.setFieldNamingStrategy(new FieldNamingStrategy() {
@Override
public String translateName(Field f) {
String fieldName = f.getName();
if(fieldName.startsWith("_") && fieldName.length() > 1) {
fieldName = fieldName.substring(1, 2).toUpperCase() + fieldName.substring(2);
}
return fieldName;
}
});
final Gson gson = builder.create();
System.out.println(gson.toJson(new ExampleBean("example", "bean")));
}
private static class ExampleBean {
private final String _firstField;
private final String _secondField;
private ExampleBean(String _firstField, String _secondField) {
this._firstField = _firstField;
this._secondField = _secondField;
}
}
}
生成
{"FirstField":"example","SecondField":"bean"}