【发布时间】:2015-09-17 12:59:27
【问题描述】:
我正在尝试使用 gson 解析包含对象数组的 JSON 文件。我在这行代码中收到“线程“主”com.google.gson.JsonSyntaxException:java.io.EOFException:第 1 行第 2 列输入结束”错误:
RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);
我对使用 gson 有点困惑,所以我认为我没有正确设置。数据格式如下:
[ {
"id": 10259,
"cuisine": "greek",
"ingredients": [
"romaine lettuce",
"black olives"
] }, {
"id": 25693,
"cuisine": "southern_us",
"ingredients": [
"plain flour",
"ground pepper",
"salt",
"tomatoes",
"ground black pepper",
"thyme"
] }]
试图读取的代码是:
inputStream = new FileReader("filepath\\file.json");
BufferedReader myReader = new BufferedReader(inputStream);
theLine = myReader.readLine();
Gson gson = new Gson();
RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);
我的RecipeList类,本来打算把recipe对象数组存储在json文件中(不过我觉得这肯定是错的)
ArrayList<Recipe> recipeArray;
public RecipeList (Recipe recipObj){
recipeArray.add(recipObj);
}
还有我的Recipe类,用于在json数组中创建每个recipe对象:
String recipeID;
String cuisine;
ArrayList<String> ingredients;
public Recipe (String id, String cuisine, ArrayList<String> ingredients){
this.recipeID = id;
this.cuisine = cuisine;
for (int k = 0; k < ingredients.size(); k++){
this.ingredients.add(ingredients.get(k));
}
}
感谢您的帮助。我对使用 gson 读取 json 文本以及如何从该数组创建单个对象感到有些困惑。
谢谢 丽贝卡
【问题讨论】: