[英]Parsing multiple json objects in java
我有要在程序中解析的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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.