android - GSON java how can i make different names between mapping and printing? -
i have json this:
{ "aggregation": { "cityagg" : { "key" : "paris" } } }
i create mapping , each field, add @serializedname
because want create custom names variables.
for example in json, there key names key
, want variable in java cityname
.
so, this:
@serializedname("key") public string cityname
i can dynamically map response json objects this:
gson gson = new gson(); query2 query2 = gson.fromjson(response, query2.class);
it working perfectly.
however, when want print mapped object, this:
string query2string = gson.tojson(query2); gson gsonpretty = new gsonbuilder().setprettyprinting().create(); string prettyjson = gsonpretty.tojson(query2string);
the problem that, in prettyjson
, can see key
, not cityname
.
i know if there way customize that. don't want see key
.
either should use custom deserializer or should alter value of annotation using reflection.
update: worst solution
using reflection looks this
classloader classloader = urlclassloader.newinstance(new url[]{yourclass.class.getresource("yourclass.class")}); class locannotation = classloader.loadclass("yourpackage.query2"); field field = locannotation.getdeclaredfield("cityname"); final annotation fieldannotation = field.getannotation(serializedname.class); changeannotationvalue(fieldannotation, "oldvalue", "newvalue"); public static object changeannotationvalue(annotation annotation, string key, object newvalue) { object handler = proxy.getinvocationhandler(annotation); field f; try { f = handler.getclass().getdeclaredfield("membervalues"); } catch (nosuchfieldexception | securityexception e) { throw new illegalstateexception(e); } f.setaccessible(true); map<string, object> membervalues; try { membervalues = (map<string, object>) f.get(handler); } catch (illegalargumentexception | illegalaccessexception e) { throw new illegalstateexception(e); } object oldvalue = membervalues.get(key); if (oldvalue == null || oldvalue.getclass() != newvalue.getclass()) { throw new illegalargumentexception(); } membervalues.put(key, newvalue); return oldvalue; }
Comments
Post a Comment