Question

So, I have a JSON file where I want to load an array within the main object, so I load it with:

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

The array called "items" that I load with

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

contains a large amount of nameless objects that all have the following structure:

            {
                "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"
                ]

            }

What I want to be able to do is get a JSONObject containing an object that I choose by filtering through the name value. For instance, I want to get all objects that have the "name" key set to "TF_WEAPON_BAT", and then store it into a JSONObject called foundItem.

Thanks in advance, Denton.

Was it helpful?

Solution

As far as I know, that library doesn't have an XPath style parser. You will need to go through the entries yourself. For example

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
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top