Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting all name-elements from a JsonObject

Tags:

java

json

arrays

I am having trouble extracting the proper information from my JsonObject. Currently, I'm receiving this type of String from a Web API:

{"start_game_items":{"11":98,"14":39,"16":120,"20":51,"27":60,"34":2,"39":5,"42":4,"44":98,"181":4,"237":13,"241":5}}

The information that I'm interested in, is every number inside the ""s, e.g "11", "14" and so forth. These numbers represents a specific item within a computer game, so they will most likely vary from each String from the Web API. Currently I'm doing this:

// below is the String that I displayed in the top "{"start_game_item":{"11"..}""
    String jsonString = itemData[0];

    JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();
    Set entrySet = jsonObject.entrySet();
    Object[] items = entrySet.toArray();

    for (Object o : items) {
        System.out.println(o.toString());
    }

But when I do this, I receive the same line as earlier posted. Can anyone see where I go wrong? I am using the google.gson library for Java.

EDIT: I had a some-what similar issue earlier, where I received this type of String:

{"1":"blink","2":"blades_of_attack","3":"broadsword","4":"chainmail","5":"claymore","6":"helm_of_iron_will","7":"javelin","8":"mithril_hammer","9":"platemail","10":"quarterstaff",..}

Where these item-numbers are mapped to a item-name. However, that was one large Array which I solved by doing this:

String jsonString = itemIDData[0];
    JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();

    Set keySet = jsonObject.keySet();
    List<String> listJsonObjectKeys = new ArrayList<String>();

    // Now we add each Key from the jsonObject to a List, so we can use the ID(Key).
    for (Object key : keySet) {
        listJsonObjectKeys.add(key.toString());
    }

    for (int i = 0; i < keySet.size(); i++) {
        String currentIDString = listJsonObjectKeys.get(i);
        JsonElement currentItem = jsonObject.get(currentIDString);

        String itemName = currentItem.getAsString();
        int currentID = Integer.parseInt(currentIDString);
        itemIDMap.put(currentID, itemName);
    }
}

I tried to use a similar logic to the issue I posted about, but I'm having issues in extracting the information I need.

like image 529
Christoffer Ashorn Avatar asked Feb 15 '26 20:02

Christoffer Ashorn


1 Answers

This is what you want:

    String jsonString = itemData[0];

    JsonObject jsonObject = JsonParser.parseString(jsonString).getAsJsonObject();

    for ( Entry e : jsonObject.getAsJsonObject( "start_game_items" ).entrySet() ) {
        System.out.println( e.getKey() );
    }
like image 163
TimonNetherlands Avatar answered Feb 18 '26 11:02

TimonNetherlands



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!