Reputation: 23
The response of the call from WebService is as follows:
{
"mobilenumber": "09999999999",
"service": "1" ,
"id": "1"
}
How do I parse received Json into objects?
@Override
public void onResponse(Call<Login> call, Response<Login> response) {
if (response.isSuccessful()) {
}
}
Upvotes: 0
Views: 2003
Reputation: 2838
Assuming you have a LoginResult
model like this:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class LoginResult {
@SerializedName("mobilenumber")
@Expose
private String mobilenumber;
@SerializedName("service")
@Expose
private String service;
@SerializedName("id")
@Expose
private String id;
public String getMobilenumber() {
return mobilenumber;
}
public void setMobilenumber(String mobilenumber) {
this.mobilenumber = mobilenumber;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Then, your Retrofit onResponse()
method should be something like this:
@Override
public void onResponse(Call<LoginResult> call, Response<LoginResult> response) {
if (response.isSuccessful()) {
LoginResult result = response.body();
String mobileNumber = result.getMobilenumber();
String service = result.getService();
String id = result.getId();
}
}
Upvotes: 2
Reputation: 1293
By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type.
A Converter which uses Gson for serialization to and from JSON. A default Gson instance will be created or one can be configured and passed to the GsonConverterFactory to further control the serialization.
Add to gradle;
compile 'com.squareup.retrofit2:converter-gson:latest.version'
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.xxx.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
Upvotes: 0
Reputation: 3838
This code gives you how to parse the json.
@Override
public void onResponse(Call<Login> call, Response<Login> response) {
if (response.isSuccessful()) {
JSONObject jsonobject = new JSONObject(yourresponse);
String mobilenumber = jsonobject.getString("mobilenumber");
String service = jsonobject.getString("service");
String id = jsonobject.getString("id");
}
Upvotes: 1