Java 解析Json数组导致这种情况不是Json数组异常
我试图解析一个Json数组,如下所示:Java 解析Json数组导致这种情况不是Json数组异常,java,json,gson,Java,Json,Gson,我试图解析一个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 sid
{
"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);
}
我有什么遗漏吗?我尝试使用中给出的以下代码,但得到了与该问题中提到的相同的异常。任何帮助都将不胜感激
Gson gson = new GsonBuilder().create();
Type collectionType = new TypeToken<List<FoodItem>>(){}.getType();
List<FoodItem> foodItems = gson.fromJson(jsonReader, collectionType);
Gson Gson=new GsonBuilder().create();
Type collectionType=new-TypeToken(){}.getType();
List foodItems=gson.fromJson(jsonReader,collectionType);
您需要更改此选项
JsonArray jarray = parser.parse(jsonReader).getAsJsonArray();
到
您的JSON在根目录下包含一个名为FoodItemData
的JSON对象。该元素包含您试图映射到列表的JSON数组
或者,您可以创建一个类,该类有一个名为FoodItemData
的字段,该字段是一个列表
另外,请注意,Java约定规定变量名应以小写字符开头。正如@Sotirios正确提到的,JSON是一个包含数组的对象,而不是一个独立数组
不过我会做一点小小的改变(我会使用getAsJsonArray
)而不是强制转换:
在FoodItem类中是否有get/set方法?我有。但我不认为这是必要的,因为Gson使用反射来设置场。
JsonArray jarray = parser.parse(jsonReader).getAsJsonArray();
JsonArray jarray = (JsonArray) parser.parse(jsonReader).getAsJsonObject().get("FoodItemData");
public class RootElement {
List<FoodItem> FoodItemData;
// the good stuff
}
RootElement root = gson.fromJson(jsonReader, RootElement.class);
System.out.println(root.FoodItemData);
JsonArray Jarray = parser.parse(jsonReader).getAsJsonObject().getAsJsonArray("FoodItemData");