I'm trying to parse the ResponseBody json object. I then need to create a WarehouseList array of Warehouse objects. Here is my response json.
{
"GetUserWarehouseListResult": [
{
"Message": null,
"WarehouseId": 31232,
"WarehouseName": "ABQ"
},
{
"Message": null,
"WarehouseId": 22113,
"WarehouseName": "AMS"
},
{
"Message": null,
"WarehouseId": 21645,
"WarehouseName": "ORD"
}
}
In objective-c, I can do this with below:
for (NSDictionary* element in [dictionary objectforKey:@"GetUserWarehouseListResult"]) {
}
However, I need help doing this in Kotlin with RetroFit2
Here is my current code:
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
val stringResponse = response.body()?.string()
Log.d(TAG,"Response: " stringResponse)
}
CodePudding user response:
You can use Converters
API in Retrofit
to integrate a third-party JSON parser library (like GSON or Moshi) with Retrofit
so that it can parse JSON responses to data classes automatically.
You can read here about how to use Converters
and implement them in Retrofit
.
CodePudding user response:
create your own model class based on your response, instead of passing ResponseBody
Like this;
public class RestResponse {
private ArrayList<GetUserWarehouseListResult> GetUserWarehouseListResult;
public ArrayList<GetUserWarehouseListResult> getGetUserWarehouseListResult () {
return GetUserWarehouseListResult;
}
public void setGetUserWarehouseListResult (ArrayList<GetUserWarehouseListResult> GetUserWarehouseListResult) {
this.GetUserWarehouseListResult = GetUserWarehouseListResult;
}
public class GetUserWarehouseListResult {
private String Message;
private String WarehouseId;
private String WarehouseName;
public String getMessage () {
return Message;
}
public void setMessage (String Message) {
this.Message = Message;
}
public String getWarehouseId () {
return WarehouseId;
}
public void setWarehouseId (String WarehouseId) {
this.WarehouseId = WarehouseId;
}
public String getWarehouseName () {
return WarehouseName;
}
public void setWarehouseName (String WarehouseName) {
this.WarehouseName = WarehouseName;
}
}
}
Now Pass this class in your retrofitCall; use 'RestResponse' instead of 'ResponseBody'
override fun onResponse(call: Call<RestResponse>, response: Response<RestResponse>) {
val responseObj: RestResponse? = response.body()
Log.d(TAG,"Response: " responseObj!!.getGetUserWarehouseListResult())
}
Hope this helps you!