我正在尝试解析一个Json数组,如下所示:
{
"FoodItemData": [
{
"country": "GB",
"id": "100",
"name": "Steak and Kidney Pie",
"description": "Tender cubes of steak, with tender lamb kidney is succulent rich gravy. Served with a side of mashed potatoes and peas.",
"category": "Dinner",
"price": "15.95"
},
{
"country": "GB",
"id": "101",
"name": "Toad in the Hole",
"description": "Plump British Pork sausages backed in a light batter. Served with mixed vegetables and a brown onion gravy.",
"category": "Dinner",
"price": "13.95"
},
{
"country": "GB",
"id": "102",
"name": "Ploughman’s Salad",
"description": "Pork Pie, Pickled Onions, Pickled relish Stilton and Cheddar cheeses and crusty French bread.",
"category": "Lunch",
"price": "10.95"
}
]
}
我正在使用Gson
解析此Json。
URL url = getClass().getClassLoader().getResource("FoodItemData.json");
FileReader fileReader = null;
try {
fileReader = new FileReader(url.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
JsonReader jsonReader = new JsonReader(fileReader);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(jsonReader).getAsJsonArray();
List<FoodItem> listOfFoodItems = new ArrayList<FoodItem>();
for (JsonElement obj : Jarray) {
FoodItem foodItem = gson.fromJson(obj, FoodItem.class);
listOfFoodItems.add(foodItem);
}
此代码导致java.lang.IllegalStateException: This is not a JSON Array
异常。FoodItem
类包含与Json中同名的变量。
public class FoodItem {
private String id;
private String name;
private String description;
private String category;
private String price;
private String country;
}
这里我遗漏了什么吗?我尝试使用this answer中给出的以下代码,但是我得到了与该问题中提到的相同的异常。如果有任何帮助,将不胜感激。
Gson gson = new GsonBuilder().create();
Type collectionType = new TypeToken<List<FoodItem>>(){}.getType();
List<FoodItem> foodItems = gson.fromJson(jsonReader, collectionType);
2条答案
按热度按时间zbdgwd5y1#
您将需要更改此设置
至
您的JSON在根位置包含一个名为
FoodItemData
的JSON对象。或者,您可以创建一个类,其中包含一个名为
FoodItemData
的字段,该字段是List<FoodItem>
并像这样解析
另外,请注意Java约定规定变量名应以小写字符开头。
rggaifut2#
正如@Sotirios正确提到的,JSON是一个包含数组的对象,而不是一个独立的数组。
我会做一个小小的改变(而不是铸造我会使用
getAsJsonArray
):