我试图使用一些json的复古装,但是看不出我的json字符串有什么问题,我一直都会遇到同样的错误。
我期待一个单词对象列表,但我错过了什么?有什么想法吗?
retrofit.converter.ConversionException: com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: 预期BEGIN_ARRAY但在第1行第2列路径$
处是BEGIN_OBJECT
JSON:
{
"words": [
{
"id": "1",
"word": "submarine",
"word_syllables": "sub-mar-ine",
"picture": "none.jpg",
"picture_dir": "",
"soundfile": "",
"user_id": "1",
"created": "2015-04-08 16:32:07",
"modified": "0000-00-00 00:00:00"
},
{
"id": "2",
"word": "computer",
"word_syllables": "com-pute-r",
"picture": "computer.jpg",
"picture_dir": "",
"soundfile": "",
"user_id": "0",
"created": "2015-04-08 16:32:07",
"modified": "0000-00-00 00:00:00"
}
]
}
改进Android代码:
private void requestData(){
RestAdapter adapter=new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.build();
WordsAPI api=adapter.create(WordsAPI.class);
api.getRestWordFeed(new Callback<List<Word>>(){
@Override
public void failure(RetrofitError arg0) {
// TODO Auto-generated method stub
Log.v("error",arg0.getMessage());
}
@Override
public void success(List arg0, Response arg1) {
// TODO Auto-generated method stub
wordList=arg0;
printList();
}
});
}
API接口:
package com.example.testretrofitlib;
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
public interface WordsAPI {
@GET("/rest_words/index.json")
public void getRestWordFeed(Callback<List<Word>> response);
}
答案 0 :(得分:3)
您的JSON是一个具有一个属性的对象:'words',它是一个word对象数组。您的错误:“预期BEGIN_ARRAY但是BEGIN_OBJECT”表示您正在等待数组,但返回了一个对象。一种解决方案是将以下内容作为json返回:
[
{
"id": "1",
"word": "submarine",
"word_syllables": "sub-mar-ine",
"picture": "none.jpg",
"picture_dir": "",
"soundfile": "",
"user_id": "1",
"created": "2015-04-08 16:32:07",
"modified": "0000-00-00 00:00:00"
},
{
"id": "2",
"word": "computer",
"word_syllables": "com-pute-r",
"picture": "computer.jpg",
"picture_dir": "",
"soundfile": "",
"user_id": "0",
"created": "2015-04-08 16:32:07",
"modified": "0000-00-00 00:00:00"
}
]
答案 1 :(得分:2)
该JSON的单词对象列表嵌入在具有“words”属性的对象的值内。该错误只是指出,它期待一个数组定界符[
,而不是找到该对象的开头。
您可以修复JSON(删除{"words": <ACTUAL_ARRAY> }
并只保留带有两个元素的数组)或修改您在getRestWordFeed中期望的数据结构。