首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用改造获得数据

无法使用改造获得数据
EN

Stack Overflow用户
提问于 2016-03-22 18:38:50
回答 1查看 1.1K关注 0票数 2

你好,我正在尝试使用改装,但我收到了以下错误:-

java.lang.IllegalStateException:预期中的BEGIN_OBJECT,但在第1列第2行路径$上是BEGIN_ARRAY

这是我的MainActivity

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {

@Bind(R.id.activity_main_tv_display)
TextView textData;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
}
@OnClick(R.id.activity_main_btn_show)
void press() {
    RemoteApi.Factory.getInstance().getModel().enqueue(new Callback<Model>() {
        @Override
        public void onResponse(Call<Model> call, Response<Model> response) {
            textData.setText(response.toString());
            Log.e("--success--", String.valueOf(response));
        }
        @Override
        public void onFailure(Call<Model> call, Throwable t) {
            Log.e("--fail--", t.getMessage());
        }
    });
  }
}

这是我的模型

代码语言:javascript
复制
public class Model {

@SerializedName("Title")
@Expose
private String Title;
@SerializedName("Message")
@Expose
private String Message;
@SerializedName("id")
@Expose
private int id;
// getters and setters declare
}

这是我的界面

代码语言:javascript
复制
public interface RemoteApi {

String BASE_URL = "xyz/";
@GET("api/Cards")
Call<Model> getModel();
class Factory {
    public static RemoteApi remoteApi;
    public static RemoteApi getInstance() {
            Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(BASE_URL)
                    .build();
            remoteApi = retrofit.create(RemoteApi.class);
            return remoteApi;
        }
    }
}

我的API看起来像这样

代码语言:javascript
复制
[{
  "Title": "xyz",
  "Message": "hello",
  "id": 1
}, {
  "Title": "abc",
  "Message": "hello",
  "id": 2
}] 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-22 18:57:08

您希望从API中获得一个对象列表(通过查看第一个字符),但是您的错误声明它需要一个对象(也是通过查看第一个字符)。在您的接口中使用的是Call<Model>,它声明您只希望返回一个Model对象,而不希望返回它们的列表。

尝试像这样设置您的界面

代码语言:javascript
复制
public interface RemoteApi {

    String BASE_URL = "xyz/";
    @GET("api/Cards")
    Call<List<Model>> getModel();

其他代码是这样的

代码语言:javascript
复制
RemoteApi.Factory.getInstance().getModel().enqueue(new Callback<List<Model>>() {
        @Override
        public void onResponse(Call<List<Model>> call, Response<List<Model>> response) {
            String responseString = String.valueOf(response);
            textData.setText(responseString);
            Log.e("--success--", responseString);
        }
        @Override
        public void onFailure(Call<List<Model>> call, Throwable t) {
            Log.e("--fail--", t.getMessage());
        }
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36162570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档