如何解析Retrofit 2对显示数据的响应?

时间:2016-01-16 11:41:35

标签: java android rest retrofit2

我想使用Retrofit 2和Gson(或GsonFormat,我不是很确定)来显示API(http://jsonplaceholder.typicode.com/posts)中的“标题”,我创建了以下类,<登记/>
Modal.java

package arpit.retrodemo;

public class Modal {
    private String title;
    public String getTitle(){
        return title;
    }
}

APIService界面,

package arpit.retrodemo;

import java.util.List;

import retrofit.Call;
import retrofit.http.GET;

public interface APIService {
    @GET("/posts")
    Call<List<Modal>> getDetails();
}


MainActivity.java

package arpit.retrodemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;


import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends AppCompatActivity {

    private static final String ENDPOINT = "http://jsonplaceholder.typicode.com";
    private APIService service;
    private static List<Modal> users;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(ENDPOINT)
                .build();
        service = retrofit.create(APIService.class);
        Call<List<Modal>> userList = service.getDetails();
        userList.enqueue(new Callback<List<Modal>>() {
            @Override
            public void onResponse(Response<List<Modal>> response) {
                if(response.isSuccess()){
                    Log.d("find", "response.isSuccess");
                    // to parse the API reponse(in JSON) to display, say, "title" from the API response
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("findError", t.getMessage());
            }
        });

    }
}


Json格式

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  }
]


所以我在onResponse方法中得到API的回复但是
如何将每个标题存储在Modal.java类的对象中,List“users”将包含Modal.java的所有对象,以便稍后使用“用户”列表上的迭代器显示标题。

2 个答案:

答案 0 :(得分:1)

1)。首先,请在你的Modal类中添加标题的setter函数。

2)。您可以从response.body()找到模态类列表。例如。

   @Override
        public void onResponse(Response<List<Modal>> response) {
            if(response.isSuccess()){
                List<Modal> titlesList=response.body();
            }
        }

答案 1 :(得分:0)

如果所有其他事情都没问题,你可以使用这段代码。

Type listType = new TypeToken<ArrayList<Modal>>() { // object can be String here
        }.getType();
        List<Modal> list = new Gson().fromJson(response.body().string(), listType);