0

The server can answer like:

{ "data1":"value", "data2":"value" } 

or:

{ "error":"text" } 

or:

{ "json":"{ "error":"text" }" }

How to parse various answers from the server using retrofit.
Maybe I should make a rich POJO like:

class MyAnswer {
   String data1;
   String data2;
   String error;
   // etc
}
d.h.
  • 1,206
  • 1
  • 18
  • 33

1 Answers1

0

I recommend you to use Google's Gson library to Serialize/Deserialize Json strings to POJO's and deserialize back. Retrofit2 also supports Gson as a converter.

Add compile 'com.squareup.retrofit2:converter-gson' to your build.gradle and create Retrofit instance like below:

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

Define your Java classes and annotate them with Gson's SerializedName tag.

public class MyAnswer {
    @SerializedName("data1")
    public String data1;

    @SerializedName("data2")
    public String data2;

    @SerializedName("error")
    public String error;
}

Then you can get your POJO on the onResponse method:

@Override
public void onResponse(Call<ExampleClass> call, Response<ExampleClass> response) {
    ExampleClass exampleClass = response.body();
    ......
}

You can also deserialize yourself from Json:

Gson gson = new GsonBuilder().create();
ExampleClass ec = gson.fromJson(jsonString, ExampleClass.class);

Or serialize to 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 also create nested/complex structures with Gson. For more information, visit their user guide.

Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37