使用 gson 解析 JSON 个对象数组

parsing JSON array of objects with gson

我正在尝试使用 gson 来解析包含对象数组的 JSON 文件。我在这行代码中收到 "Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 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 class,本来是用来在json文件中存放食谱对象数组的(但我想这一定是错的)

ArrayList<Recipe> recipeArray;

public RecipeList (Recipe recipObj){
    recipeArray.add(recipObj);
}

还有我的食谱 class,用于在 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;
                }