2016-06-13 126 views
0

我想實施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.

回答

1

我認爲你的服務器響應Feature對象數組,但是你給出了Pojo引起的問題。

嘗試使用作爲您的泛型類將被用作JSON pojo,你的問題應該被解決。

+0

謝謝您的建議!我會看看它是否會解決問題:) –

+0

它的工作!謝謝! –

+1

歡迎。我將編輯你的問題,因爲這發生在POJO中給出響應的任何庫上:) –

0

您的對象類未映射爲json響應,請使用Postman獲取響應並粘貼響應here以獲取對象中的正確參數。

相關問題