简体   繁体   中英

android - Retrofit 2:Correct way of Parsing JSON with multiple arrays

I have started using retrofit:2.0.2 first time into my new project and I have done with first service call using retrofit but am not sure is it correct way or not here is what i have done

web services response

{
  "status": true,
  "message": "",
  "data": {
    "schools": [ { "id": "1", "name": "test 1" }, { "id": "2", "name": "test 12" }],
    "referrals": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
    "Brands": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
    "Teams": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
    "positions": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
  }
}

created 3 model classes to map above response

 public class SimpleObject {
    int id;
    String name;

// getter setter
}

public class SimpleData {

    private List<SimpleObject> schools = new ArrayList<SimpleObject>();
    private List<SimpleObject> referrals = new ArrayList<SimpleObject>();
    private List<SimpleObject> positions = new ArrayList<SimpleObject>();
    private List<SimpleObject> Teams = new ArrayList<SimpleObject>();
    private List<SimpleObject> Brands = new ArrayList<SimpleObject>();

// getter, setter
}


public class ResponseData{

    boolean status;
    String message;
    SimpleData data;

    //    getter setter
}

and then made a service call using Retrofit2

call.enqueue( new Callback<ResponseData>() {
  @Override
  public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {

  }

  @Override
  public void onFailure(Call<ResponseData> call, Throwable t) {

  }

and its working fine but a want to insure that is it best way of doing this or can any one suggest the best way of handling such a response without creating multiple model classes for simple data (there should me only one model class "SimpleObject" and other will be list of "SimpleObject")

Please comment or suggest best way to handling response thanks.

The way you currently have it structured looks correct. You need to have one model for every nested level in the JSON response, which you have.

The only other option is simply breaking the object up using keys to pull all of the JSONObjects and JSONArrays, which I do not recommend.

copy and paste your json response in the link given below and download zip file and put it in your project directly.

This link will convert your any kind of json response and convert it into POJO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM