java - Using GSON to parse mixed type fields? -
how can use gson mixed type fields, possible?
{ 'field': false } // or { 'field': [ 1,2,3,4 ] }
my gson class:
public class mymodel { public hashmap<arraylist,boolean> blockedusers; }
yes possible, have handle if json array or primitive type. try code below:
string case1 = "{'field':false}"; string case2 = "{'field':[1,2,3,4]}"; jsonelement jsonelement = ((jsonobject)(new jsonparser().parse(case1))).get("field"); if(jsonelement instanceof jsonarray) { jsonarray jsonarray = (jsonarray)jsonelement; if(jsonarray != null && jsonarray.size() > 0) { (jsonelement ajsonelement : jsonarray) { // todo: handle json element inside array system.out.println(ajsonelement); } } } else if (jsonelement instanceof jsonprimitive) { boolean value = jsonelement.getasboolean(); system.out.println("value:" + value); }
also can write custom typeadapter
. see my answer question.
Comments
Post a Comment