java - 使用 gson 解析 JSON 对象数组

标签 java arrays json 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;
                }

关于java - 使用 gson 解析 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32630921/

相关文章:

java - 如何将 HTML 从数字转换为文字

javascript - 连接文本以获得变量名称 VUE2

javascript - 对象已排序,但未使用 lodash sortBy 保留其键

python - 如何在 Django 中将 Http Post 参数的 Json 值转换为 Python Dict?

php - jquery从其他页面获取数据并输入表单字段

Java:使用.txt文件将每行的特定索引分配给数组列表

java - 如何从适配器外部获取 ListView 项的 subview

c - 数组值无故改变

json - PostgreSQL:防止多重插入上的 SQL 注入(inject)

java - 如何使用 View 持有者模式制作自定义适配器?