好吧,我知道很多這樣的問題已經被問到,但我有一個具體的問題,其他問題都沒有。我想知道如何繼續使用GSON解析JSON文件。預期BEGIN_ARRAY,但是當使用GSON時BEGIN_OBJECT
{
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "51"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "55"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "0"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "51"
},
"BUYER": {
"IGN": "MGlolenstine",
"ProductID": "56"
}
}
,因爲當我使用此代碼
Scanner scanner = new Scanner(new File(path));
String text = scanner.useDelimiter("\\A").next();
Gson gson = new GsonBuilder().create();
ArrayList<Purchases> p = gson.fromJson(new FileReader(path), Purchases.class);
for(int i = 0; i < p.size(); i++){
arg0.sendMessage(ChatColor.GOLD+"Player: "+p.get(i).BUYER.IGN);
arg0.sendMessage(ChatColor.GOLD+"ProductID: "+String.valueOf(p.get(i).BUYER.ProductID));
}
scanner.close();
我得到的錯誤
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 12
這裏只是發表我的類的JSON代碼
public class Purchases{
PlayerRank BUYER;
}
public class PlayerRank{
String IGN;
int ProductID;
}
的問題可能是我不知道JS如何ON數組和對象看起來像。 有人能請解釋我的JSON代碼中的JSONArray和JSONObject的區別嗎?
預先感謝您。
編輯:所以這是固定的JSON
{
"buyers" : [
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "55" },
{ "IGN" : "MGlolenstine", "ProductID" : "0" },
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "56" }
]
}
修正Java代碼:
Scanner scanner = new Scanner(new File(path));
String text = scanner.useDelimiter("\\A").next();
Gson gson = new GsonBuilder().create();
Purchases p = gson.fromJson(new FileReader(path), Purchases.class);
for(int i = 0; i < p.buyers.length; i++){
arg0.sendMessage(ChatColor.GOLD+"Player: "+p.buyers[i].IGN);
arg0.sendMessage(ChatColor.GOLD+"ProductID: "+String.valueOf(p.buyers[i].ProductID));
}
最後是類:
public class Purchases{
PlayerRank buyers[];
}
public class PlayerRank{
String IGN;
int ProductID;
}
感謝大家尋求幫助!
你能後的Puchases類。除了我發佈的關於JSON格式的內容之外,您傳遞給gson的類必須鏡像文件。 – Juan
我在問題中添加了類部分。感謝您的回覆 –