gpt4 book ai didi

java - java中解析多个json对象

转载 作者:行者123 更新时间:2023-12-01 10:41:51 27 4
gpt4 key购买 nike

我正在尝试在程序中解析这个 json 文件。

{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}

我正在打印 JSON 字符串,但不是获取单个对象(0、然后 1、然后 2 等...),而是每次打印时只获取整个数组。

Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;

JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}

任何人都知道如何解析这个文件(没有 GSON,属性是一个自定义类,我发现使用 gson 附带的自动解析很复杂)。

最佳答案

您发现 GSON 有哪些问题?

如果将其作为 JSONObject 类传递给 gson.fromJSON,它应该可以工作,并且您将能够从 JSON 对象获取数据。

  Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);

然后你就可以调用

JsonArray array = jsonFile.get("items").getAsJsonArray();

然后从数组的第一个元素中获取属性。

 array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

关于java - java中解析多个json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34378133/

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