【发布时间】:2018-01-05 22:23:15
【问题描述】:
我有以下 JSON 结构:
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "qui est esse",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
}
]
我正在尝试使用 Retrofit 2.x 使用此 JSON。我正在尝试获取用户列表。
这是我的APIService interface:
public interface APIService {
@POST("posts")
Call<List<FakeJSON>> getItems();
}
这是我的 POJO 类:
public class FakeJSON {
@SerializedName("userId")
@Expose
private int userId;
@SerializedName("id")
@Expose
private int id;
@SerializedName("title")
@Expose
private String title;
@SerializedName("body")
@Expose
private String body;
/**
* No args constructor for use in serialization
*
*/
public FakeJSON() {
}
/**
*
* @param id
* @param body
* @param title
* @param userId
*/
public FakeJSON(int userId, int id, String title, String body) {
super();
this.userId = userId;
this.id = id;
this.title = title;
this.body = body;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
最后是我的Activity 代码,我在其中进行网络调用:
public class NetworkActivity extends AppCompatActivity {
private static Retrofit.Builder builder = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
builder = new Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit =
builder
.client(
httpClient.build()
)
.build();
APIService apiService = retrofit.create(APIService.class);
Call<List<FakeJSON>> listCall = apiService.getItems();
listCall.enqueue(new Callback<List<FakeJSON>>() {
@Override
public void onResponse(Call<List<FakeJSON>> call, Response<List<FakeJSON>> response) {
try {
Log.e("List Size", response.body().size()+"");
}catch (NullPointerException e){
e.printStackTrace();;
}
}
@Override
public void onFailure(Call<List<FakeJSON>> call, Throwable t) {
Log.e("Error", t.getMessage());
}
});
}
}
每当我运行应用程序时,我都会收到以下异常:
E/错误:应为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT
我在这里做错了什么?
【问题讨论】:
-
检查这可能对你有帮助:stackoverflow.com/a/38351872/6021469
-
已经看过了。对我没用:(
-
这是我的错误。我做了一个
@POST而不是@GET:)