我正在尝试使用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类,用于在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文本以及如何从该数组创建单个对象感到困惑。
感谢 丽贝卡
答案 0 :(得分:1)
theLine = myReader.readLine();
你需要从文件中读取所有行直到eof。
例如:
br = new BufferedReader(new FileReader("C:\\testing.txt"));
String line="";
while ((line = br.readLine()) != null) {
theLine+=line;
}