gpt4 book ai didi

java - 预期为 BEGIN_ARRAY,但使用 GSON 时为 BEGIN_OBJECT

转载 作者:行者123 更新时间:2023-11-30 06:45:01 25 4
gpt4 key购买 nike

好吧,我知道很多人都问过类似的问题,但我有一个具体的问题,其他人都没有。我想知道如何继续使用 GSON 解析以下 JSON 文件。

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

问题可能是我不知道 JSON 数组和对象是什么样的。有人可以解释一下我的 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));
}

最后是类(class):

public class Purchases{
PlayerRank buyers[];
}

public class PlayerRank{
String IGN;
int ProductID;
}

感谢大家的帮助!

最佳答案

JSON 对象直接括在大括号 {} 中,而 JSON 数组则括在 JSON 对象内的方括号 [] 中。

Purchases 和 PlayerRank 类应该这样定义:

public class Purchases{
@SerializedName("buyers") protected ArrayList<PlayerRank> buyers;

...
}

public class PlayerRank{
@SerializedName("IGN") protected String ign;
@SerializedName("ProductID") protected int productId;

...
}

请注意 SerializedName 表示法,它允许您将 json 文件中的对象/数组的名称与 java 属性的名称解耦。

我添加到属性中的 protected 只是明确了原始代码中原始类的默认值。

JSON 文件应该是这样的:

{
"buyers" : [
{ "IGN": "MGlolenstine", "ProductID": "51"},
{ "IGN": "MGlolenstine", "ProductID": "55"},
...
{ "IGN": "MGlolenstine", "ProductID": "56"}
]
}

并将 JSON 读入变量:

Purchases p = gson.fromJson(new FileReader(path), Purchases.class);

关于java - 预期为 BEGIN_ARRAY,但使用 GSON 时为 BEGIN_OBJECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43821497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com