[英]parsing JSON array of objects with gson
我正在尝试使用gson解析包含对象数组的JSON文件。 我在此代码行上收到“线程“ main”中的异常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类,旨在将配方对象数组存储在json文件中(但我认为这一定是错误的)
ArrayList<Recipe> recipeArray;
public RecipeList (Recipe recipObj){
recipeArray.add(recipObj);
}
还有我的Recipe类,用于在json数组中创建每个配方对象:
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文本以及如何从该数组创建单个对象,我有些困惑。
谢谢丽贝卡
theLine = myReader.readLine();
您需要从文件读取所有行,直到eof。
例如:
br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line="";
while ((line = br.readLine()) != null) {
theLine+=line;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.