我想實施Retrofit到我的應用程序來與我的服務器端點進行通信。我在後臺有一個叫做「Feature」的表,它有id:number,name:text和roomID:number字段。我不明白我做錯了什麼。我嚴格遵循了Retrofit文檔。我得到這個錯誤,當我嘗試從我的數據庫ID獲取特定的功能,我得到這個錯誤:預計BEGIN_ARRAY,但是BEGIN_OBJECT Android Json
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
這是我的主要活動:
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.
謝謝您的建議!我會看看它是否會解決問題:) –
它的工作!謝謝! –
歡迎。我將編輯你的問題,因爲這發生在POJO中給出響應的任何庫上:) –