如何解析 JSON 对象的响应数组,其中数组没有键名

How to parse JSON response Array of object, where array is without key name

我正在尝试解析没有数组名称的 json 结果。这是我的 json 回复:

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

如何使用 com.squareup.retrofit2:retrofit:2.1.0 库解析它?

创建一个Class喜欢,

class Test {

     public List<TestValue> testValues;
}

然后调用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) {

    }
});

使用您的模型class,这仅用于示例目的。

通常你可以解析为

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();
    }

如果您想使用 Model Class 解析它,那么您的 Model Class 将用于 Retrofit

 class Response
{

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

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

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

}

并像那样定义改造回调

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

希望这会有所帮助