my json string looks following:
{ "text": ["foo",1,"bar","2",3], "text1": "value1", "complexobject": { ..... } } i have pojo defined this:
class mypojo { list<string> text; string text1; complexobject complexobject; } i use google gson , able java object populated properly. problem here field text array of mixed types (string , int). entries there converted string , not able figure out entries in array string vs int. cant use parseint since entries in original array may have "2" 3.
is there way me right instance type of fields in array after converting java object.
solution
so implemented solution using gson round way using jsondeserializer. , tried using jackson. guess jackson supports serializing/deserializing mixed array type preserving data types.
objectmapper mapper = new objectmapper(); mypojo gmentry = mapper.readvalue(json, new typereference<mypojo >(){}); and can fetch list<object> , instanceof check datatype.
shame on gson!!
by having custom class , adding type adapter u can manipulate string (json.tostring() returns '"' quotes, can see if string or not.
output: (the classes seem correct)
class test.main$stringpojo pojo{object=foo}
class test.main$intpojo pojo{object=1}
class test.main$stringpojo pojo{object=bar}
class test.main$stringpojo pojo{object=2}
class test.main$intpojo pojo{object=3}
public static void main(final string[] args){ string str = "{\n" + " \"text\": [\"foo\",1,\"bar\",\"2\",3],\n" + " \"text1\": \"value1\" }"; gsonbuilder builder = new gsonbuilder(); builder.registertypeadapter(pojo.class, new jsondeserializer<pojo>() { @override public pojo deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { try { return new intpojo(integer.parseint(json.tostring())); } catch (exception e) { return new stringpojo(json.getasstring()); } } }); mypojo mypojo = builder.create().fromjson(str, mypojo.class); (pojo pojo : mypojo.text) { system.out.println(pojo.getclass() + " " + pojo.object); } } public static abstract class pojo{ protected object object; public pojo() { } @override public string tostring() { return "pojo{" + "object=" + object + '}'; } } public static class stringpojo extends pojo{ public stringpojo(string str) { object = str; } } public static class intpojo extends pojo{ public intpojo(int intt) { this.object = intt; } } public static class mypojo { list<pojo> text; string text1; }
Comments
Post a Comment