Convert JSON String to generic object in JAVA (with GSON) -
i have api returns json. response in format can fit object called apiresult , contains context <t>
, int code.
apiresult declared in generic way, e.g. apiresult<someobject>
i know how gson convert incoming json string apiresult<t>
so far have:
type apiresulttype = new typetoken<apiresult<t>>() { }.gettype(); apiresult<t> result = gson.fromjson(json, apiresulttype);
but still returns converts context linkedhashmap instead (which assume gson falls to)
you have know t going be. incoming json fundamentally text. gson has no idea object want become. if there's in json can clue off of create t instance, can this:
public static class myjsonadapter<x> implements jsondeserializer<apiresult<x>> { public apiresult<x> deserialize( jsonelement jsonelement, type type, jsondeserializationcontext context ) throws jsonparseexception { string classname = jsonelement.getasjsonobject().get( "_class" ).getasstring(); try { x mything = context.deserialize( jsonelement, class.forname( classname ) ); return new apiresult<>(mything); } catch ( classnotfoundexception e ) { throw new runtimeexception( e ); } } }
i'm using field "_class" decide x needs , instantiating via reflection (similar pompom's example). don't have such obvious field, there has way @ jsonelement , decide based on what's itn type of x should be.
this code hacked version of similar did gson while back, see line 184+ at: https://github.com/chriskessel/myhex/blob/master/src/kessel/hex/domain/gameitem.java
Comments
Post a Comment