the server can answer like:
{ "data1":"value", "data2":"value" }
or:
{ "error":"text" }
or:
{ "json":"{ "error":"text" }" }
how parse various answers server using retrofit.
maybe should make rich pojo like:
class myanswer { string data1; string data2; string error; // etc }
i recommend use google's gson library serialize/deserialize json strings pojo's , deserialize back. retrofit2 supports gson converter.
add compile 'com.squareup.retrofit2:converter-gson'
build.gradle , create retrofit instance below:
retrofit retrofit = new retrofit.builder() .baseurl(base_url) .client(client) .addconverterfactory(gsonconverterfactory.create()) .build();
define java classes , annotate them gson's serializedname
tag.
public class myanswer { @serializedname("data1") public string data1; @serializedname("data2") public string data2; @serializedname("error") public string error; }
then can pojo on onresponse method:
@override public void onresponse(call<exampleclass> call, response<exampleclass> response) { exampleclass exampleclass = response.body(); ...... }
you can deserialize json:
gson gson = new gsonbuilder().create(); exampleclass ec = gson.fromjson(jsonstring, exampleclass.class);
or serialize json:
exampleclass ec = new exampleclass(); ec.data1 = "some text"; ec.data2 = "another text"; gson gson = new gsonbuilder().create(); string jsonstring = gson.tojson(ec);
you can create nested/complex structures gson. more information, visit their user guide.
Comments
Post a Comment