Minkyu Kim Minkyu Kim - 4 months ago 15
Java Question

Gson FieldNamingStrategy with multiple policies

I want to map underscored field(such as

this_field_to_mapped
) to camelcase(
thisFieldToMapped
).

So I created
Gson
object with
GsonBuilder
and coded a new class implemented
FieldNamingStrategy
and
SomeClass
.

And I'd run
Gson.fromJson
from
{"thisItem" : "hello", "this_field_to_mapped":1}
, but console log had printed out like this.


replaced : thisItem

replaced : thisFieldToMapped

hello

0


thisItem
was mapped well, however
thisFieldToMapped
had printed 0.

How can I map underscored field to camelcase ?

here's my code.


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;
}

}


And this is main method

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);
}
}

Answer

You're doing this backwards. The javadoc for FieldNamingStrategy states

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.

Also, the javadoc of FieldNamingStrategy#translateName(String) states

Translates the field name into its JSON field name representation.

As you can tell, what you receive as an argument to translateName is the Field itself. translateName is meant to convert the name of that field to a name that will appear in the JSON.

So you need to convert thisFieldToMapped to this_field_to_mapped. You're attempting to do the opposite.

If all your JSON members were named with underscores, you could use FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES as a strategy.

Comments