为什么我们使用呼叫列表与改造

问题描述 投票:0回答:2

我有一个例子,我想了解一些部分,在这个考试中,它工作得很好,但当我把部分从:call list<model>> method();改为:call <model> method();

导致了一个错误,这是什么原因?这两种情况有什么区别?

// MainActivity :
public class MainActivity extends AppCompatActivity {



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

            GetData service = RetrofitClient.getRetrofitInstance().create(GetData.class);

            Call<RetroUsers> call = service.getAllUsers();

            call.enqueue(new Callback<RetroUsers>() {
                @Override
                public void onResponse(Call<RetroUsers> call, Response<RetroUsers> response) {
                    Log.i("print", "" + response.body().getUser());
                }

                @Override
                public void onFailure(Call<RetroUsers> call, Throwable t) {
                    Log.i("print", "Dont" + t.getMessage());
                }
            });

        }



    ///Error message :
    I/print: Dontjava.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $


    // interface GetData:
    public interface GetData {
        @GET("/users")
        Call<RetroUsers>getAllUsers();
        /*
        @GET("/users")
        Call<List<RetroUsers>> getAllUsers();
        */
    }

    // RetrofitClient :
    public class RetrofitClient {

        private static Retrofit retrofit;
        private static final String BASE_URL = "https://jsonplaceholder.typicode.com";


        public static Retrofit getRetrofitInstance() {
            if (retrofit == null) {
                retrofit = new retrofit2.Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }



       // model class :

        public class RetroUsers {

            @SerializedName("name")
            private String name;


            public RetroUsers(String name) {
                this.name = name;

            }

            public String getUser() {
                return name;
            }

            public void setUser(String name) {
                this.name = name;
            }



        }
java android retrofit2
2个回答
0
投票

导致..: Call<RetroUsers> getAllUsers();

因为getAllUsers()会返回多个RetroUsers记录,所以会导致错误。由于这一点,它需要你为它提供一个类型为List,这样它的数据类型就被设置为List,然后它就可以处理多条记录。

通过Core Java的基础知识来更好地理解这一点。


0
投票

在一种情况下,你告诉反序列化器,你期望的是 单个 Model在另一种情况下,你告诉它期待一个模型列表,也就是一个 List<Model>. 根据你实际得到的数据,你需要使用其中一个或另一个.当然,你可以 "隐藏 "List< ...> 在你的模型中,通过不使用 "List< ...> 。List<Model> 但。

public class MoreThanOneModel {
    public List<Model> entries;
    ...
}

但这并没有改变基本的推理。

© www.soinside.com 2019 - 2024. All rights reserved.