Tuesday, 15 July 2014

android - How do I convert a successful Response body to a specific type using retrofit? -



android - How do I convert a successful Response body to a specific type using retrofit? -

in async mode retrofit calls

public void success(t t, response rawresponse)

were t converted response, , rawresponse raw response. provides access both raw response , converted response.

in sync mode can either converted response or raw response

converted response

@get("/users/list") list<user> userlist();

raw response

@get("/users/list") response userlist();

the response object have method body

typedinput getbody()

and retrofit api have converter class can convert java object

object frombody(typedinput body,type type)

but can not figure out how instance of converter object

i might able create instance of converter class, require knowledge of gson object used create restadapter, may not have access to. ideally, obtain reference converter object straight restadpater.

any of next reply question: is there way reference default converter used retrofit? does know how default converter constructed? (there no default constructor , there 2 constructors public gsonconverter(gson gson) , public gsonconverter(gson gson, string charset) is there other way both raw , converted response in sync mode?

here's illustration of stringconverter class implements converter found in retrofit. you'll have override frombody() , tell want.

public class stringconverter implements converter { /* * in default cases retrofit calls on gson expects json gives * next error, com.google.gson.jsonsyntaxexception: * java.lang.illegalstateexception: expected begin_object * begin_array @ line x column x */ @override public object frombody(typedinput typedinput, type type) throws conversionexception { string text = null; seek { text = fromstream(typedinput.in()); } grab (ioexception e) { e.printstacktrace(); } homecoming text; } @override public typedoutput tobody(object o) { homecoming null; } // custom method convert stream request string public static string fromstream(inputstream in) throws ioexception { bufferedreader reader = new bufferedreader(new inputstreamreader(in)); stringbuilder out = new stringbuilder(); string newline = system.getproperty("line.separator"); string line; while ((line = reader.readline()) != null) { out.append(line); out.append(newline); } homecoming out.tostring(); } }

applying request you'll have following:

// initializing retrofit's rest adapter restadapter restadapter = new restadapter.builder() .setendpoint(apiconstants.main_url).setloglevel(loglevel.full) .setconverter(new stringconverter()).build();

android retrofit

No comments:

Post a Comment