java - Gson FieldNamingStrategy with multiple policies -
i want map underscored field(such this_field_to_mapped) camelcase(thisfieldtomapped).
so created gson object gsonbuilder , coded new class implemented fieldnamingstrategy , someclass.
and i'd run gson.fromjson {"thisitem" : "hello", "this_field_to_mapped":1}, console log had printed out this.
replaced : thisitem
replaced : thisfieldtomapped
hello
0
thisitem mapped well, thisfieldtomapped had printed 0.
how can map underscored field camelcase ?
here's 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 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); } }
you're doing backwards. javadoc fieldnamingstrategy states
a mechanism providing custom field naming in gson. allows client code translate field names particular convention not supported normal java field declaration rules.
also, javadoc of fieldnamingstrategy#translatename(string) states
translates field name json field name representation.
as can tell, receive argument translatename field itself. translatename meant convert name of field name appear in json.
so need convert thisfieldtomapped this_field_to_mapped. you're attempting opposite.
if json members named underscores, use fieldnamingpolicy.lower_case_with_underscores strategy.
Comments
Post a Comment