我想将下划线字段(例如 this_field_to_mapped
)映射到驼峰式(thisFieldToMapped
)。
因此,我使用 GsonBuilder
创建了 Gson
对象,并编写了一个实现了 FieldNamingStrategy
和 SomeClass
的新类。
我会从 {"thisItem": "hello", "this_field_to_mapped":1}
运行 Gson.fromJson
,但控制台日志打印如下.
replaced : thisItem
replaced : thisFieldToMapped
hello
0
thisItem
映射得很好,但是 thisFieldToMapped
打印了 0。
如何将下划线字段映射到驼峰命名法?
这是我的代码。
SomeClass
public static class SomeClass {
public String thisItem;
public int thisFieldToMapped;
}
UnderScoreToUpper
public static class UnderScoreToUpper implements FieldNamingStrategy {
public String translateName(Field f) {
String name = f.getName();
Pattern p = Pattern.compile("[_][a-z]{1}");
Matcher m = p.matcher(name);
while (m.find()) {
System.out.println("matched : " + m.group(0));
String c = m.group(0).replace("_", "").toUpperCase();
name = name.replace(m.group(0), c);
}
System.out.println("replaced : " + name);
return name;
}
}
这是主要方法
public static void main(String[] args) {
String gsonString = "{\"thisItem\" : \"hello\", \"this_field_to_mapped\":1}";
Gson g = new GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.setFieldNamingStrategy(new UnderScoreToUpper())
.serializeSpecialFloatingPointValues().setPrettyPrinting()
.serializeNulls().create();
SomeClass c = g.fromJson(gsonString, SomeClass.class);
if (c != null) {
System.out.println(c.thisItem);
System.out.println(c.thisFieldToMapped);
}
}
最佳答案
你这是在倒退。 FieldNamingStrategy
的 javadoc州
A mechanism for providing custom field naming in Gson. This allows the client code to translate field names into a particular convention that is not supported as a normal Java field declaration rules.
此外,FieldNamingStrategy#translateName(String)
的 javadoc州
Translates the field name into its JSON field name representation.
正如您所知,您收到的 translateName
参数是 Field
本身。 translateName
旨在将该字段的名称转换为将出现在 JSON 中的名称。
因此您需要将 thisFieldToMapped
转换为 this_field_to_mapped
。您正试图做相反的事情。
如果所有 JSON 成员都使用下划线命名,则可以使用 FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES
作为策略。
关于java - 具有多个策略的 Gson FieldNamingStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38579412/