java - Gson, how to deserialize array or empty string -
i trying deserialize json array of objects:
[{ "name": "item 1", "tags": ["tag1"] }, { "name": "item 2", "tags": ["tag1","tag2"] }, { "name": "item 3", "tags": [] }, { "name": "item 4", "tags": "" }]
my java class looks this:
public class myobject { @expose private string name; @expose private list<string> tags = new arraylist<string>(); }
the problem json's tags property can empty string or array. right gson gives me error: com.google.gson.jsonsyntaxexception: java.lang.illegalstateexception: expected begin_array string
how should deserialize json?
i not have control json, comes 3rd pary api.
i not have control json, comes 3rd pary api.
if don't have control on data, best solution create custom deserializer in opinion:
class myobjectdeserializer implements jsondeserializer<myobject> { @override public myobject deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { jsonobject jobj = json.getasjsonobject(); jsonelement jelement = jobj.get("tags"); list<string> tags = collections.emptylist(); if(jelement.isjsonarray()) { tags = context.deserialize(jelement.getasjsonarray(), new typetoken<list<string>>(){}.gettype()); } //assuming there appropriate constructor return new myobject(jobj.getasjsonprimitive("name").getasstring(), tags); } }
what it checks whether "tags"
jsonarray
or not. if it's case, deserializes usual, otherwise don't touch , create object empty list.
once you've written that, need register within json parser:
gson gson = new gsonbuilder().registertypeadapter(myobject.class, new myobjectdeserializer()).create(); //here json string contains input list<myobject> myobjects = gson.fromjson(json, new typetoken<list<myobject>>(){}.gettype());
running it, output:
myobject{name='item 1', tags=[tag1]} myobject{name='item 2', tags=[tag1, tag2]} myobject{name='item 3', tags=[]} myobject{name='item 4', tags=[]}
Comments
Post a Comment