2013-11-05 18 views
3

我試圖解析一個JSON數組,看起來像這樣:造成這種解析JSON數組是不是一個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); 
+0

你有讓你FoodItem類/ set方法? – jagmohan

+0

我是。但我不認爲這是必要的,因爲Gson使用反射來設置字段。 – Rajath

回答

9

你需要改變這種

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約定規定變量名稱應以小寫字符開頭。

+1

非常感謝!得到它的工作。 – Rajath

1

正如@Sotirios正確提到的,您的JSON是一個包含數組而不是獨立數組的對象。

我會做一個細微的變化,但(而不是鑄造我會用getAsJsonArray):

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