×
您的位置: 首页 > 编程笔记

解析Json数组导致这不是JSON数组例外(Parsing Json Array resulting in This is not a JSON Array exception)

JSON 时间:2020-06-15  查看:788   收藏

I am trying to parse a Json array which looks like this:

{
  "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"
      }
]
}

I am using Gson to parse this 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);
        }

This code results in java.lang.IllegalStateException: This is not a JSON Array exception. The FoodItem class contains the variables with the same name as in the Json.

public class FoodItem {
    private String id;
    private String name;
    private String description;
    private String category;
    private String price;
    private String country;
}

Am I missing anything here? I tried using the following code as given in this answer, but I got the same exception as the one mentioned in that question. Any help would be appreciated.

Gson gson = new GsonBuilder().create();
Type collectionType = new TypeToken<List<FoodItem>>(){}.getType(); 
List<FoodItem> foodItems = gson.fromJson(jsonReader, collectionType);

解决方案

You will need to change this

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

to

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

Your JSON contains a JSON object at the root called FoodItemData. That element contains the JSON array you are trying to map to a List<FoodItem>

Alternatively, you could create a class that has a field called FoodItemData that is a List<FoodItem>

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

And parse like so

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

Also, note that Java convention states that variable names should start with a lower case character.



  {
FoodItemData:[ 
 {
country:GB,
id:100,
name:Steak and Kidney Pie,
description :嫩牛排块,嫩羔羊肉是多汁丰富的肉汁,配上土豆泥和豌豆的一面。,
类别:晚餐,
价格: 15.95
,
 {
country:GB,
id:101,
name:Toad in the Hole ,
描述:丰满的英国猪肉香肠以浅色面糊为背景,配以混合蔬菜和棕色洋葱肉汁。,
类别:晚餐,
价格:13.95
},
 {
country:GB,
id:102,
name: Ploughman's Salad,
description:猪肉馅饼,腌洋葱,腌制的Stilton和切达干酪,
类别:午餐,
价格:10.95
} 
] 
}



我使用 Gson 来解析这个Json。



  URL url = getClass()。getClassLoader()。getResource(FoodItemData.json); 

 FileReader fileReader = null; 
尝试{
 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(); 

列表< FoodItem> listOfFoodItems = new ArrayList< FoodItem>(); (JsonElement obj:Jarray)

 {
 FoodItem foodItem = gson.fromJson(obj,FoodItem.class); 
 listOfFoodItems.add(foodItem); 
}



此代码导致 java.lang.IllegalStateException:这不是JSON数组异常。  FoodItem 类包含与Json中相同名称的变量。



  public class FoodItem {
 private String id; 
私人字符串名称; 
私有字符串描述; 
私有字符串类别; 
私人字符串价格; 
私人字符串国家; 
}



我在这里遗漏了什么吗?我尝试使用中给出的以下代码答案,但我得到了与该问题中提到的例外相同的例外。任何帮助将不胜感激。



  Gson gson = new GsonBuilder()。create(); 
 Type collectionType = new TypeToken< List< FoodItem>>(){}。getType(); 
列表< FoodItem> foodItems = gson.fromJson(jsonReader,collectionType);


解决方案

您需要更改这个



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





   



您的JSON在根目录中包含一个名为 FoodItemData $ c的JSON对象$ C>。该元素包含您试图映射到 List< FoodItem>



的JSON数组或者,您可以创建一个名为 FoodItemData 的字段,它是一个 List< FoodItem>



  public class RootElement {
 List< FoodItem> FoodItemData; 
 //好东西
}



像这样解析



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






另外请注意,Java约定规定变量名应该以小写字母开始。


 

0% (0)
0% (0)