[英]Converting JSON Array from Server API request to objects in retrofit2
I have a server where I query to get a list of topics in a forum. 我有一台服务器,可以在其中查询以获取论坛中的主题列表。 The data returned via
curl
is something like this - 通过
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",
....
}
]
Here every JSONObject
is a data about forum topic. 在这里,每个
JSONObject
都是关于论坛主题的数据。
{
"id": 554,
"date": "2015-06-07T21:16:28",
"date_gmt": "2015-06-07T15:46:28",
....
}
I want to display this data in a ListView
in an Android app. 我想在Android应用程序的
ListView
中显示此数据。
However, since I am using retrofit2
and gson
to create the objects for the ListView
, the response I always get is Not Found
. 然而,由于我使用
retrofit2
和gson
以创建对象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();
Right now I am not doing anything when deserializing the returned JSON
. 现在,当反序列化返回的
JSON
时,我什么也不做。 Even if I use a JsonDeserializer
, how should I go about it such that it is easier to populate the List<Forum>
. 即使使用
JsonDeserializer
,也应该如何处理它,以便更轻松地填充List<Forum>
。
You dont need to change JSON itself. 您不需要更改JSON本身。
public interface ServerAPI {
@GET("/forum")
Call<Forum> getListOfForums();
}
FormResponse.java FormResponse.java
public class ForumResponse {
@SerializedName("id")
private int id;
@SerializedName("date")
private String date;
@SerializedName("date_gmt")
private String date_gmt;
}
onResponse
in MainActivity.java 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.