[英]parsing JSON array of objects with 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.