2016-06-13 88 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以获取对象中的正确参数。

相关问题