Thursday, 15 March 2012

android - Parse JSON with variable key in retrofit -



android - Parse JSON with variable key in retrofit -

i'm working on application retrofit library i'm not in charge of backend.

this json receive when there error. illustration when parameter 'email' wrong json response:

{"status":"error","errors":{"email":{"emailnotfound":"email not found"}}}

now 'email' part parameter wrong. how create object can reuse multiple parameters.

i have this:

public class authenticateresponse { @expose private string status; @expose private error errors; @expose private string session; public string getstatus() { homecoming status; } public void setstatus(string status) { this.status = status; } public string getsession() { homecoming session; } public void setsession(string session) { this.session = session; } public error geterrors() { homecoming errors; } public void seterrors(error errors) { this.errors = errors; } }

but don't know how create error object because key variable. in case it's 'email' it's different.

i have this

public class errors { private list<object> list; public list<object> getlist() { homecoming list; } public void setlist(list<object> list) { this.list = list; } }

but 'list' not key in json doesn't work. solutions ?

i found solution. can register type adapter in retrofit :

gson gson = new gsonbuilder() .registertypeadapter(errors.class, new erroradapter()) .create();

than pass converter restadapter

restadapter restadapter = new restadapter.builder() .setendpoint(endpoint) .setrequestinterceptor(requestinterceptor) .setconverter(new gsonconverter(gson)) .build();

and in erroradapter parse json manually

public static class erroradapter implements jsondeserializer<errors> { @override public errors deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { errors errors = new errors(); seek { if (json != null) { jsonobject jsonobject = json.getasjsonobject(); (map.entry<string, jsonelement> elementjson : jsonobject.entryset()) { jsonobject error = elementjson.getvalue().getasjsonobject(); string errorvalue = error.entryset().iterator().next().getkey(); errors.adderror(errorvalue); } } } grab (exception e) { errors = null; } homecoming errors; } }

android json retrofit

No comments:

Post a Comment