gpt4 book ai didi

java - Gson 嵌套无名数组

转载 作者:行者123 更新时间:2023-11-30 02:02:44 26 4
gpt4 key购买 nike

我正在使用 GSon 为我正在制作的游戏解析卡片列表,但我似乎遇到了困难。我试图解析的 json 是:

{
"name": "Core Set 2019",
"code": "M19",
"releaseDate": "2018-07-13",
"border": "black",
"type": "core",
"booster": [
[
"rare",
"mythic rare"
],
"uncommon",
"uncommon",
"uncommon",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"common",
"land",
"marketing"
]
}

问题出现在助推器部分。 netbeans 给出的错误消息是

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:Expected a string but was BEGIN_ARRAY at line 9 column 8 path $.M19.booster[0]

到目前为止我的代码是:

public class Set
{
public String name;
public String code;
public String releaseDate;
public String border;
public String type;
public List<String> booster;
public Translation translations;
public List<Card> cards;
}

主要是我有

Gson g = new GsonBuilder().create();
Set sets = g.fromJson(new FileReader(JSONNAME), Set.class);

如何解析数组对象中的无名数组?无名数组并不总是存在,而且我无法更改 json,因为它是从我无权访问的网站下载的。

最佳答案

将您的类(class)更改为此类(class):

public class JsonResponse
{
private String name;
private String code;
private String releaseDate;
private String border;
private String type;
ArrayList< Object > booster = new ArrayList < Object > ();


public String getName() {
return name;
}

public String getCode() {
return code;
}

public String getReleaseDate() {
return releaseDate;
}

public String getBorder() {
return border;
}

public String getType() {
return type;
}


public void setName(String name) {
this.name = name;
}

public void setCode(String code) {
this.code = code;
}

public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}

public void setBorder(String border) {
this.border = border;
}

public void setType(String type) {
this.type = type;
}

@Override
public String toString() {
return "JsonResponse{" +
"name='" + name + '\'' +
", code='" + code + '\'' +
", releaseDate='" + releaseDate + '\'' +
", border='" + border + '\'' +
", type='" + type + '\'' +
", booster=" + booster +
'}';
}
}

就我而言,我将其放在 /resources/jsonexample.json 上,所以我这样做了:

Gson gson = new Gson();
try {
JsonResponse jsonResponse = gson.fromJson(new FileReader(new File("resources/jsonexample.json")), JsonResponse.class);
System.out.println(jsonResponse.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}

输出是

JsonResponse{name='Core Set 2019', code='M19', releaseDate='2018-07-13', border='black', type='core', booster=[[rare, mythic rare], uncommon, uncommon, uncommon, common, common, common, common, common, common, common, common, common, common, land, marketing]}

我已经创建了一个存储库来说明如何在 Github 上执行此操作

关于java - Gson 嵌套无名数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52283643/

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