0
我想用gson来解析包含对象数组的JSON文件。我发现了主要是“在线程异常‘’com.google.gson.JsonSyntaxException:java.io.EOFException的:输入完第1行第2列”的错误在这条线的代码:用gson解析对象的JSON数组
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);
}
我的食谱类的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文本以及如何从该数组创建单个对象感到困惑。
感谢 丽贝卡
似乎已经清除了该错误消息。我不知道其他人是否仍在阅读该文件(其相当大)。鉴于它的大文件有没有办法处理它,而不会变成1长串? json文件中的行分隔符是什么?它是在数组中的每个对象之后还是任意的? – marsupials
其实你必须阅读完整的文件。文件dos的格式不会改变其JSON或其他文件。在将其解析为GSON之前,您需要一个完整的JSON。我找不到任何帮助。但是如果你认为占用Java堆很多,你可以使用StringBuilder而不是String。 –
我认为你可以从InputStream解析GSON而不是使用也可以提供帮助的String。 Gson gson = new Gson(); Reader reader = new InputStreamReader(source); SearchResponse response = gson.fromJson(reader,SearchResponse.class); 这里的来源将是你的文件。 –