【问题标题】:Converting JSON Array from Server API request to objects in retrofit2将 JSON 数组从服务器 API 请求转换为改造 2 中的对象
【发布时间】:2016-04-23 10:19:39
【问题描述】:

我有一个服务器,我在其中查询以获取论坛中的主题列表。通过curl 返回的数据是这样的 -

[
  {
    "id": 728,
    "date": "2016-01-01T13:01:51",
    "date_gmt": "2016-01-01T07:31:51",
    ....
  },
  {
    "id": 556,
    "date": "2015-06-07T21:16:59",
    "date_gmt": "2015-06-07T15:46:59",
    ....
  },
  {
    "id": 554,
    "date": "2015-06-07T21:16:28",
    "date_gmt": "2015-06-07T15:46:28",
    ....
  }
]

这里每一个JSONObject都是一个论坛主题的数据。

{
  "id": 554,
  "date": "2015-06-07T21:16:28",
  "date_gmt": "2015-06-07T15:46:28",
  ....
}

我想在 Android 应用中以ListView 显示此数据。

但是,由于我使用retrofit2gsonListView 创建对象,所以我总是得到Not Found 的响应。

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(ENDPOINT)
        .addConverterFactory(buildGsonConverter())
        .build();

serverAPI = retrofit.create(ServerAPI.class);

private Converter.Factory buildGsonConverter() {
    return GsonConverterFactory.create();
}

Call<List<Forum>> call = App.serverAPI.getListOfForums();
call.enqueue(new Callback<List<Forum>>() {
    @Override
    public void onResponse(Call<List<Forum>> call, Response<List<Forum>> response) {
        Log.i(TAG, "onResponse: " + (null != response.message() ? response.message() : ""));
        Log.i(TAG, "response body - " + (null != response.body() ? response.body() : ""));
        if (response.isSuccessful()) {
            adapter.setForums(response.body());
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onFailure(Call<List<Forum>> call, Throwable t) {
        Log.i(TAG, "onFailure: " + t.toString());
        Log.i(TAG, "onFailure: " + t.getMessage());
    }
});

ServerAPI.class - 

@GET("/forum/")
Call<List<Forum>> getListOfForums();

现在我在反序列化返回的JSON 时没有做任何事情。即使我使用JsonDeserializer,我应该如何处理它以便更容易填充List&lt;Forum&gt;

【问题讨论】:

    标签: java android json gson retrofit2


    【解决方案1】:

    您不需要更改 JSON 本身。

    public interface ServerAPI {
       @GET("/forum")
       Call<Forum> getListOfForums();
     }
    

    FormResponse.java

    public class ForumResponse {
      @SerializedName("id")
      private int id;
    
      @SerializedName("date")
      private String date;
    
      @SerializedName("date_gmt")
      private String date_gmt;
    }
    

    MainActivity.java 中的onResponse

    @Override
    public void onResponse(Call<Forum> call, Response<Forum> response) {
        String jsonString = response.body().toString();
        Log.i("onResponse", jsonString);
        Type listType = new TypeToken<List<ForumResponse>>() {}.getType();
        List<ForumResponse> yourList = new Gson().fromJson(jsonString, listType);
        Log.i("onResponse", yourList.toString());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 2021-07-03
      • 2019-02-17
      • 1970-01-01
      • 2017-10-15
      • 2017-02-25
      • 2016-07-20
      • 2014-11-07
      相关资源
      最近更新 更多