简体   繁体   English

用gson解析对象的JSON数组

[英]parsing JSON array of objects with gson

I'm trying to use gson to parse a JSON file containing an array of objects. 我正在尝试使用gson解析包含对象数组的JSON文件。 I'm getting a "Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2" error on this line of code: 我在此代码行上收到“线程“ main”中的异常com.google.gson.JsonSyntaxException:java.io.EOFException:第1列第2列的输入结束”错误:

  RecipeList[] myRecipe = gson.fromJson(theLine, RecipeList[].class);

I am a bit confused about using gson so I don't think I've set things up properly. 我对使用gson感到有些困惑,因此我认为我没有正确设置所有内容。 The data is in this format: 数据采用以下格式:

[  {
"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"
]  }]

the code trying to read that is: 试图读取的代码是:

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);

my RecipeList class, which was intended to store the array of recipe objects in the json file (but I think this must be wrong) 我的RecipeList类,旨在将配方对象数组存储在json文件中(但我认为这一定是错误的)

ArrayList<Recipe> recipeArray;

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

And my Recipe class, for the creation of each recipe object in the json array: 还有我的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));
    }
}  

I appreciate any help. 感谢您的帮助。 I'm a bit confused over the reading of the json text using gson and how to create the individual objects from that array. 对于使用gson读取json文本以及如何从该数组创建单个对象,我有些困惑。

thanks Rebecca 谢谢丽贝卡

theLine = myReader.readLine(); theLine = myReader.readLine();

you need to read all lines from file until eof. 您需要从文件读取所有行,直到eof。

ex: 例如:

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM