为什么用retrofit2不能得到响应?

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

我以前没怎么用过 retrofit,但在这个项目中,我会用 retrofit。但在这个项目中,我将使用 retrofit。当尝试从服务器获得响应时,无法获得响应。它使这个错误。

java.lang.IllegalStateException: 期待BEGIN_OBJECT,但在第1行第2列的路径上是BEGIN_ARRAY。

这有什么问题吗?

这是我的postman结果。

enter image description here

ApiInterface. java

public interface ApiInterface {
    @GET("/categories/0")
    Call<Category> getCategoryList();
}

ApiClient.java

public class ApiClient {

    private static Retrofit retrofit;
    private static final String BASE_URL = MyConstants.URL;

    public static Retrofit getRetrofitInstance() {

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

CategoryFragment.java

public class CategoriesFragment extends Fragment {

    RecyclerView mRecyclerView;
    List<Category> categoryList;
    Category category;

    public CategoriesFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_categories, container, false);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(mGridLayoutManager);

        ApiInterface apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
        Call<Category> call = apiInterface.getCategoryList();
        call.enqueue(new Callback<Category>() {
            @Override
            public void onResponse(Call<Category> call, Response<Category> response) {
                if (response.isSuccessful()) {
                    Category category_list = response.body();
                    Log.d("cateogry", "");
                    // CategoryAdapter myAdapter = new CategoryAdapter(getActivity(), categoryList);
                    //      mRecyclerView.setAdapter(new CategoryAdapter(category, R.layout.category_item_view, ));
                    // mRecyclerView.setAdapter(myAdapter);
                }
                else
                  //  ApiErrorUtils.parseError(response);
                  Log.d("Api hata", "");
            }

            @Override
            public void onFailure(Call<Category> call, Throwable t) {
                Log.d("Error", t.getMessage());
            }
        });

        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
  //                  + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
java android json retrofit2
4个回答
1
投票

你的 API 答复希望 Object 但实际反应是 Array. 你应该使用 List<Category> 而不是 <Category>......像以下

public interface ApiInterface {

    @GET("/categories/0")
    Call<List<Category>> getCategoryList();
}

而API调用应该像下面这样。

Call<List<Category>> call = apiInterface.getCategoryList();
        call.enqueue(new Callback<List<Category>>() {
            @Override
            public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
                if (response.isSuccessful()) {
                    List<Category> category_list = response.body();
                    Log.d("cateogry",category_list.size());
                    // CategoryAdapter myAdapter = new CategoryAdapter(getActivity(), categoryList);
                    //      mRecyclerView.setAdapter(new CategoryAdapter(category, R.layout.category_item_view, ));
                    // mRecyclerView.setAdapter(myAdapter);
                }
                else
                  //  ApiErrorUtils.parseError(response);
                  Log.d("Api hata", "");
            }

            @Override
            public void onFailure(Call<List<Category>> call, Throwable t) {
                Log.d("Error", t.getMessage());
            }
        });

1
投票

这是我在后端团队将数组改成对象时常见的错误。

问题是在你的模型类(pojo类)中的某处 你被声明为一个数组,但实际上它是一个对象(或者反之亦然)。


1
投票

你所使用的响应是不正确的,你需要像这样纠正它

json响应示例

{
  "category": [
    {
      "categoryID": 5,
      "categoryName": "Name",
      "categoryImage": "path",
      "categoryProductCount": 0,
      "hasSubCategory": false  
    },
{
    "categoryID": 5,
    "categoryName": "Name",
    "categoryImage": "path",
    "categoryProductCount": 0,
    "hasSubCategory": false
    }
  ]
}

现在,你应该在接口中使用POJO类。

public class MyPojo
{
    private List<Category> category;

    public List<Category>  getCategory ()
    {
        return category;
    }

    public void setCategory (List<Category> category)
    {
        this.category = category;
    }


}

哪儿 Category 类是

public class Category
{
    private String categoryImage;

    private String hasSubCategory;

    private String categoryName;

    private String categoryID;

    private String categoryProductCount;

    public String getCategoryImage ()
    {
        return categoryImage;
    }

    public void setCategoryImage (String categoryImage)
    {
        this.categoryImage = categoryImage;
    }

    public String getHasSubCategory ()
    {
        return hasSubCategory;
    }

    public void setHasSubCategory (String hasSubCategory)
    {
        this.hasSubCategory = hasSubCategory;
    }

    public String getCategoryName ()
    {
        return categoryName;
    }

    public void setCategoryName (String categoryName)
    {
        this.categoryName = categoryName;
    }

    public String getCategoryID ()
    {
        return categoryID;
    }

    public void setCategoryID (String categoryID)
    {
        this.categoryID = categoryID;
    }

    public String getCategoryProductCount ()
    {
        return categoryProductCount;
    }

    public void setCategoryProductCount (String categoryProductCount)
    {
        this.categoryProductCount = categoryProductCount;
    }

  }

**Usage**

public interface ApiInterface {
    @GET("/categories/0")
    Call<MyPojo> getCategoryList();
}

在零散的CategoriesFragment类

public class CategoriesFragment extends Fragment {

    RecyclerView mRecyclerView;
    List<Category> categoryList;
    Category category;

    public CategoriesFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_categories, container, false);
        mRecyclerView = view.findViewById(R.id.recyclerview);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
        mRecyclerView.setLayoutManager(mGridLayoutManager);

        ApiInterface apiInterface = ApiClient.getRetrofitInstance().create(ApiInterface.class);
        Call<MyPojo> call = apiInterface.getCategoryList();
        call.enqueue(new Callback<MyPojo>() {
            @Override
            public void onResponse(Call<MyPojo> call, Response<MyPojo> response) {
                if (response.isSuccessful()) {
                    categoryList = response.body().getCategory ();
                     CategoryAdapter myAdapter = new CategoryAdapter(getActivity(), categoryList);
                          mRecyclerView.setAdapter(new CategoryAdapter(category, R.layout.category_item_view, ));
                    // mRecyclerView.setAdapter(myAdapter);
                }
                else
                  //  ApiErrorUtils.parseError(response);
                  Log.d("Api hata", "");
            }

            @Override
            public void onFailure(Call<MyPojo> call, Throwable t) {
                Log.d("Error", t.getMessage());
            }
        });

        return view;
    }



     // TODO: Rename method, update argument and hook method into UI event
        public void onButtonPressed(Uri uri) {
            if (mListener != null) {
                mListener.onFragmentInteraction(uri);
            }
        }
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
//            throw new RuntimeException(context.toString()
  //                  + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

0
投票

改造帮助器 用kotlin编写的库,只需几行代码就能让你调用API。

在你的应用类中添加像这样的头文件。

class Application : Application() {

    override fun onCreate() {
    super.onCreate()

        retrofitClient = RetrofitClient.instance
                    //api url
                .setBaseUrl("https://reqres.in/")
                    //you can set multiple urls
        //                .setUrl("example","http://ngrok.io/api/")
                    //set timeouts
                .setConnectionTimeout(4)
                .setReadingTimeout(15)
                    //enable cache
                .enableCaching(this)
                    //add Headers
                .addHeader("Content-Type", "application/json")
                .addHeader("client", "android")
                .addHeader("language", Locale.getDefault().language)
                .addHeader("os", android.os.Build.VERSION.RELEASE)
            }

        companion object {
        lateinit var retrofitClient: RetrofitClient

        }
    }  

然后进行调用。

retrofitClient.Get<GetResponseModel>()
            //set path
            .setPath("api/users/2")
            //set url params Key-Value or HashMap
            .setUrlParams("KEY","Value")
            // you can add header here
            .addHeaders("key","value")
            .setResponseHandler(GetResponseModel::class.java,
                object : ResponseHandler<GetResponseModel>() {
                    override fun onSuccess(response: Response<GetResponseModel>) {
                        super.onSuccess(response)
                        //handle response
                    }
                }).run(this)

更多信息请看 文件

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