java - 解析 Json 数组导致 This is not a JSON Array 异常

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

最佳答案

你需要改变这个

JsonArray jarray = parser.parse(jsonReader).getAsJsonArray();

JsonArray jarray = (JsonArray) parser.parse(jsonReader).getAsJsonObject().get("FoodItemData");

您的 JSON 在根目录中包含一个名为 FoodItemData 的 JSON 对象.该元素包含您尝试映射到 List<FoodItem> 的 JSON 数组

或者,您可以创建一个类,其中包含一个名为 FoodItemData 的字段那是一个List<FoodItem>

public class RootElement {
    List<FoodItem> FoodItemData;
    // the good stuff
}

然后像这样解析

RootElement root = gson.fromJson(jsonReader, RootElement.class);
System.out.println(root.FoodItemData);

另请注意,Java 约定规定变量名应以小写字符开头。

关于java - 解析 Json 数组导致 This is not a JSON Array 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19780576/

相关文章:

javascript - D3JS - 在 setinterval 刷新时更改颜色(也称为 ragging)

java - HashMap to gson with maps as values

java - 当格式已知时从 String 解析 JSON 的最快方法

java - 如何使用 Web 客户端在 Apache CXF JAX-RS 中发送带有正文的 DELETE 请求?

java - 如何在 Java 中将 Badgerfish 风格的 JSON 转换为 XML?

json - 如何编写 Serde Visitor 将字符串数组转换为 Vec<Vec<f64>>?

Android GSON 自定义反序列化

java - 有没有办法对Java中的每个线程设置最大内存使用限制?

Java/Scala - 将 xml 转换为 json

javascript - HTML 中的有向图表示