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.