0

所以,我有一个 JSON 文件,我想在主对象中加载一个数组,所以我加载它:

try {
    schemaData = (JSONObject) parser.parse(new FileReader(schema));
    schemaItemDataArray = (JSONArray) schemaData.get("items");
} catch (IOException | ParseException e) {
    e.printStackTrace();
}

我加载的名为“items”的数组

schemaItemDataArray = (JSONArray) schemaData.get("items");

包含大量无名对象,它们都具有以下结构:

            {
                "name": "TF_WEAPON_BAT",
                "defindex": 0,
                "item_class": "tf_weapon_bat",
                "item_type_name": "Bat",
                "item_name": "Bat",
                "proper_name": false,
                "item_slot": "melee",
                "model_player": "models\/weapons\/w_models\/w_bat.mdl",
                "item_quality": 0,
                "image_inventory": "backpack\/weapons\/c_models\/c_bat",
                "min_ilevel": 1,
                "max_ilevel": 1,
                "image_url": "http:\/\/media.steampowered.com\/apps\/440\/icons\/c_bat.d037d6a40ec30ab4aa009387d476dca889b6f7dc.png",
                "image_url_large": "http:\/\/media.steampowered.com\/apps\/440\/icons\/c_bat_large.0ac4b6f335f671bd6b5e6ae02f47985af2da8c48.png",
                "craft_class": "weapon",
                "craft_material_type": "weapon",
                "capabilities": {
                    "nameable": true,
                    "can_craft_mark": true,
                    "can_be_restored": true,
                    "strange_parts": true,
                    "can_card_upgrade": true,
                    "can_strangify": true,
                    "can_consume": true
                },
                "used_by_classes": [
                    "Scout"
                ]

            }

我想要做的是获得一个 JSONObject ,其中包含我通过过滤名称值来选择的对象。例如,我想获取所有将“name”键设置为“TF_WEAPON_BAT”的对象,然后将其存储到一个名为 foundItem 的 JSONObject 中。

在此先感谢,丹顿。

4

1 回答 1

0

据我所知,该库没有 XPath 样式解析器。您需要自己浏览这些条目。例如

JSONObject object = new JSONObject("{\"items\": [{\"name\":\"TF_WEAPON_BAT\"}, {\"name\":\"TF_WEAPON_BAT\"}]}");

JSONArray array = object.getJSONArray("items");
for (int i = 0; i < array.length(); i++) {
    String name = array.getJSONObject(i).getString("name");
    if ("TF_WEAPON_BAT".equals(name)) {
        // do something
        JSONObject foundItem = array.getJSONObject(i); // this holds the object that had a matching name element
        // you can add it to some other list
    }
}
于 2013-09-15T23:14:34.647 回答