【问题标题】:How to parse JSON response Array of object, where array is without key name如何解析对象的JSON响应数组,其中数组没有键名
【发布时间】:2018-12-29 02:46:45
【问题描述】:

我正在尝试解析没有数组名称的 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 库解析这个?

【问题讨论】:

标签: android json retrofit2 jsonparser


【解决方案1】:

创建一个类,

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) {

    }
});

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

【讨论】:

    【解决方案2】:

    通常你可以解析为

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

    希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 2012-09-20
      • 2018-12-22
      • 2018-06-08
      • 1970-01-01
      相关资源
      最近更新 更多