预期 BEGIN_ARRAY 但实际 BEGIN_OBJECT Android Json

Expected BEGIN_ARRAY but was BEGIN_OBJECT Android Json

我正在尝试在我的应用程序中实施 Retrofit 以与我的服务器端点进行通信。我在后端有一个名为 "Feature" 的 Table,它有 id: number、name: text 和 roomID:number 字段。我不明白我做错了什么。我严格遵守 Retrofit 文档。当我尝试通过 ID 从我的数据库中获取特定功能时出现此错误我收到此错误:

IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
06-13 17:21:20.896 15174-15180/xdesign.georgi.espc_retrofit W/art: Suspending all threads took: 5.681ms

这是我的主Activity:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);


            final Call<Feature> call = gitHubService.repoContributors(173);

            call.enqueue(new Callback<Feature>() {
                @Override
                public void onResponse(Call<Feature> call, Response<Feature> response) {
                    Log.e("MainActivity","onResponce");
                    final TextView textView = (TextView) findViewById(R.id.textView);
                    textView.setText(response.body().toString());
                }

                @Override
                public void onFailure(Call<Feature> call, Throwable t) {
                    Log.e("MainActivity","onFailure" + t.toString());
                    final TextView textView = (TextView) findViewById(R.id.textView);
                    textView.setText("Something went wrong: " + t.getMessage());
                }


            });
        }
    });
}

GitHutService.java

interface GitHubService {
@GET("Features/{id}")
Call<Feature> repoContributors(@Path("id") int id);


public static final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://10.0.2.2:3000/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
}

Feature.java

public class Feature {

String name;
int roomID;

public String getName() {
    return name;
}

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

public int getRoomID() {
    return roomID;
}

public void setRoomID(int roomID) {
    this.roomID = roomID;
}

@Override
public String toString() {
    return "Feature{" +
            "name='" + name + '\'' +
            ", roomID=" + roomID +
            '}';
}
}

Note : This issue can happen in any networking library which parses the JSON response and gives the final Java POJO back.

我认为您的服务器响应了 Feature 对象数组,但您给出的 Pojo 导致了问题。

尝试使用通用 class 作为 JSON 的 pojo,您的问题应该会得到解决。

您的对象 class 未映射为 json 响应,请使用 Postman to get the response and paste the response here 获取对象中的正确参数。