我正在尝试使用 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;
}
关于java - 使用 gson 解析 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32630921/