-1

I am trying to parse json result without array name. Here is my json response:

[
    {
        "Id": 2293,
        "Name": "Dr.",
        "Active": true
    },
    {
        "Id": 2305,
        "Name": "Mr.",
        "Active": true
    },
    {
        "Id": 2315,
        "Name": "Mrs.",
        "Active": true
    }
]

How to parse this using com.squareup.retrofit2:retrofit:2.1.0 library?

James Z
  • 12,209
  • 10
  • 24
  • 44
Harry
  • 369
  • 2
  • 17

2 Answers2

1

Create One Class Like,

class Test {

     public List<TestValue> testValues;
}

Then call API,

Call<List<Test>> getTestData(@Field("xyz") String field1);


   Call <List<Test>> call = service.getTestData("val");

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

        List<Test> rs = response.body();

    }

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

    }
});

User Your Model class, this is only for example purpose.

Janak
  • 607
  • 5
  • 23
0

Normally you can parse as

String response = "[{"Id": 2293,"Name": "Dr.","Active": true},{"Id": 2305,"Name": "Mr.","Active": true},{"Id": 2315,"Name": "Mrs.","Active": true}]";
    try {
        JSONArray ja = new JSONArray(response);
        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = ja.getJSONObject(i);
            String id = jo.getString("Id");
            String name = jo.getString("Name");
            String active = jo.getString("Active");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

If you want to parse it using Model Class then your Model Class will be for Retrofit

 class Response
{

    @SerializedName("Id")
    @Expose
    private String id;

    @SerializedName("Name")
    @Expose
    private String name;

    @SerializedName("Active")
    @Expose
    private String active;

}

and define Callback for retrofit like that

Call<List<Meeting>> getMeetings(@Field String data );

Hope this will help

Sukhbir
  • 1,410
  • 14
  • 33