[英]Parsing multiple json objects in java
I have this json file that I'm trying to parse in my program. 我有要在程序中解析的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}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out. 我正在打印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());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with). 任何人都对如何解析此文件有一个想法(没有GSON,属性是一个自定义类,我发现使用gson随附的自动解析非常复杂)。
What did you find troubling with GSON? 您发现GSON有什么困扰?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object. 如果将它作为JSONObject类传递给gson.fromJSON,它应该可以工作,并且可以从JSON对象获取数据。
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call 那你可以打电话
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array. 然后从数组的第一个元素中获取属性。
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.