簡體   English   中英

將JSON數組從Server API請求轉換為Retrofit2中的對象

[英]Converting JSON Array from Server API request to objects in retrofit2

我有一台服務器,可以在其中查詢以獲取論壇中的主題列表。 通過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中顯示此數據。

然而,由於我使用retrofit2gson以創建對象ListView ,響應我總是得到的是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<Forum>

您不需要更改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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM