在 android 中改造 - 在 json 中使用对象而不是数组

Retrofit in android - use object Instead of array in json

我将 Retrofit 用于 get 和 Parse Json 但我遇到了问题

告诉我这个错误

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

我的json

 {
"status": "ok",
"item": [
{
"name": "joe"
},
{
"name": "jack"
},
{
"name": "sara"
}
]
}

我的界面

    public interface api{
    @GET("/api/get.php")
    Call<List<Repo>> listRepos();
}

主要活动

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();

        api service = retrofit.create(api.class);

        Call<List<Repo>> call = service.listRepos();
        call.enqueue(this);

@Override
    public void onResponse(Response<List<Repo>> response, Retrofit retrofit) {
        // specify an adapter (see also next example)
        mAdapter = new RepoAdapter(response.body());
        mRecyclerView.setAdapter(mAdapter);
        for (Repo repo : response.body()) {
            Log.i(TAG, repo.getName());
        }
    }

    @Override
    public void onFailure(Throwable t) {
        Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        Log.e(TAG,t.getMessage());
    }

我的模型

public class Repo {



       private String name;
        private  String status;

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getName() {
            return name;
        }

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


    }

我无法解析 有谁能够帮助我。谢谢

您的改装界面需要一个列表,但这不是您的 API return 想要的。你需要一个能够正确表示响应体的class,比如下面的:

class ListReposResponse {
    String status;
    List<Repo> item;
}

然后你的改造方法需要 return 那 class 而不是 List<Repo>.

@GET("/api/get.php")
Call<ListReposResponse> listRepos();