Ok, I know that many of questions like that have been asked, but I have a specific question, which none of the others has. I want to know how I'd go on to parse following JSON file with GSON.
{
"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"
}
}
because when I use this code
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();
I get the error
Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 12
Here just posting the classes I have for the JSON code
public class Purchases{
PlayerRank BUYER;
}
public class PlayerRank{
String IGN;
int ProductID;
}
The problem is probably me not knowing how the JSON arrays and objects look like. Could someone please explain the difference between JSONArray and JSONObject in my JSON code?
Thank you in advance.
EDIT: So this is the fixed JSON
{
"buyers" : [
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "55" },
{ "IGN" : "MGlolenstine", "ProductID" : "0" },
{ "IGN" : "MGlolenstine", "ProductID" : "51" },
{ "IGN" : "MGlolenstine", "ProductID" : "56" }
]
}
Fixed Java code:
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));
}
And lastly the classes:
public class Purchases{
PlayerRank buyers[];
}
public class PlayerRank{
String IGN;
int ProductID;
}
Thanks to everyone for the help!