我的课程:
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”的documentation,但我很惊讶不提供跳过“_”的选项 我也知道我可以使用注释...
@ SerializedName (" custom_naming ")
...但是我不想为alllllll我的领域写这个...
区分局部变量和类的字段对我非常有用。 :(任何想法?
编辑:会有很多明显的解决方案,(继承,gson覆盖方法,常规表达)。我的问题更侧重于是否存在gson的原生解决方案或更少侵入性的修复?
也许我们可以建议新的FieldNamePolicy?
答案 0 :(得分:13)
GsonBuilder
提供了一种方法setFieldNamingStrategy()
,可让您通过自己的FieldNamingStrategy
实施。
请注意,这会取代对setFieldNamingPolicy()
的调用 - 如果您查看GsonBuilder
的来源,这两个方法是互斥的,因为它们设置了相同的内部字段(FieldNamingPolicy
枚举< em>是 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"
}
答案 1 :(得分:0)
你想要的是
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"}