'Trying to get a child key value from a json object saved in an map-variable in sketchware

i have the following json as a get response:

{
    "global": {
        "name": "Lz Cha0S",
        "uid": xxx,
        "platform": "X1",
        "level": 521,
        "toNextLevelPercent": 31,
        "internalUpdateCount": 22822,
        "bans": {
            "isActive": false,
            "remainingSeconds": 0,
            "last_banReason": "COMPETITIVE_DODGE_COOLDOWN"
        },
        "rank": {
            "rankScore": 4227,
            "rankName": "Gold",
            "rankDiv": 2,
            "rankImg": "https:\/\/api.apexlegendsstatus.com\/assets\/ranks\/gold2.png"
        },
        "battlepass": {
            "level": "-1"
        }
    },
    "realtime": {
        "lobbyState": "open",
        "isOnline": 0,
        "isInGame": 0,
        "canJoin": 0,
        "partyFull": 0,
        "selectedLegend": "Bloodhound"
    },
    "legends": {
        "selected": {
            "LegendName": "Bloodhound",
            "data": [
                {
                    "name": "Kills",
                    "value": 331,
                    "key": "kills"
                },
                {
                    "name": "Beast of the hunt kills",
                    "value": 62,
                    "key": "beast_of_the_hunt_kills"
                },
                {
                    "name": "Season 4 Wins",
                    "value": 20,
                    "key": "wins_season_4"
                }
            ],
            "ImgAssets": {
                "icon": "http:\/\/api.apexlegendsstatus.com\/assets\/icons\/bloodhound.png",
                "banner": "http:\/\/api.apexlegendsstatus.com\/assets\/banners\/bloodhound.jpg"
            }
        },
        "all": {cutted becouse off to much Text...},
    "mozambiquehere_internal": {
        "isNewToDB": false,
        "claimedBy": "-1",
        "APIAccessType": "BASIC",
        "ClusterID": "2",
        "rate_limit": {
            "max_per_second": 3,
            "current_req": "1"
        }
    },
    "total": {
        "kills": {
            "name": "Kills",
            "value": 331
        },
        "beast_of_the_hunt_kills": {
            "name": "Beast of the hunt kills",
            "value": 62
        },
        "wins_season_4": {
            "name": "Season 4 Wins",
            "value": 20
        },
        "kd": {
            "value": -1,
            "name": "KD"
        }
    }
}

I saved this json to a map with the skecthware block

Json [response] to Map [response]json to map block

Now a want to get the name key with is in the global key, but if i use the block

Map [response] get key [name] Map get key name

It gives a error that name cannot be found (null exeption)

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference at com.chaos droid.attack.MainActivity$3.onResponse(MainActivity.java:365) se(MainActivity.java:365) at com.chaosdroid.attack.RequestNetwork er$3$2.run(RequestNetworkController.java:171) at android.os.Handler.handleCallback(Handler.java:

873) at

android.os.Handler.dispatchMessage(Handler.ja va:99) at android.os.Looper.loop(Looper.java:193) at android.app.Activity Thread.main(ActivityThread.j ava:6718) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491) ArgsCaller.run(RuntimeInit.java:491)

at com.android.internal.os.ZygoteInit.main(Zygotel nit.java:858)

END APPLICATION

If i use the global key in the get key block it returns the global key as Text

Map [response] get key [global] get map key global

returns

{name=Lz Cha0S, uid=xxx, platform=X1, level=521.0, toNextLevelPercent=31.0, internalUpdateCount=22822.0, bans={isActive=false, remainingSeconds=0.0, last_banReason=COMPETITIVE_DODGE_COOLDOWN}, rank={rankScore=4227.0, rankName=Gold, rankDiv=2.0, rankImg=https://api.apexlegendsstatus.com/assets/ranks/gold2.png}, battlepass={level=-1}}

i tried to save that output to a New map variable but its not a valid json objet so the json to map block is not working.

It looks like the map value can store only one key with value not a child key. When i get the response where i have an error in the get field it returns an error json that looks like this:

{"Error": "Player not found. Try again?"}

Here can i get the key succsessful with the same get key block: Map [response] get key [global] Get map.key error

i also tried to parse the json with Java in an add source directly block with:


JSONObject jObject = new JSONObject(result);

String aJsonString = jObject.getString("name");

But then i get a sketchware Compiler error that jsonobjet cannot be resolved to a type


1. ERROR in /storage/emulated/0/.sketchware/mysc/717/app/src/main/ java/com/chaosdroid/atrack/MainActivity.java (at line 355) String result = response;

Type mismatch: cannot convert from HashMap<String,Object> to String

2. ERROR in /storage/emulated/0/.sketchware/mysc/717/app/src/main/ java/com/chaos droid/attack/MainActivity.java (at line 357) JSONObject jObject = new JSONObject(result);

JSONObject cannot be resolved to a type

3. ERROR in /storage/emulated/0/.sketchware/mysc/717/app/src/main/ java/com/chaosdroid/atrack/MainActivity.java (at line 357) JSONObject Object = new JSONObject(result);

JSONObject cannot be resolved to a type

3 problems (3 errors)

And i dont know how to import jsonobject into sketchware.

How can a get the child key of global from this json?

Edit: (thanks to @Dmytro Kyrychkov)

For sketchware users: you need the full declaration of the function you want to use because you cant import libraries in sketchware. For this example this will working in an add source directly block in sketchware:

String jsonStr = strResponse; 
Gson gson = new Gson(); 
HashMap<String, Object> json = gson.fromJson(jsonStr, HashMap.class);
com.google.gson.internal.LinkedTreeMap<String, Object> global = (com.google.gson.internal.LinkedTreeMap<String, Object>) json.get("global"); 
String name = (String) global.get("name"); 


Solution 1:[1]

If you want to get a JSON object child field you should follow its structure during parsing:

public static void main(String... args) throws IOException {
    String jsonStr = new String(Files.readAllBytes(PATH_TO_JSON));
    Gson gson = new Gson();
    HashMap<String, Object> json =  gson.fromJson(jsonStr, HashMap.class);
    LinkedTreeMap<String, Object> global = (LinkedTreeMap<String, Object>) json.get("global");
    String name = (String) global.get("name");
    System.out.println(name);
}

Output:

Lz Cha0S
Process finished with exit code 0

I hope it helps you :)

Solution 2:[2]

  1. Create two map variables, map1 and map2

  2. now get your response in map1

  3. and then use Json[map:[map1]get kay "global"] to map:[map2]],

Now you have your JSON data ready to use with ListMap, remember that your JSON data is now inside map2, so whenever you want to use it remember to get it from map2.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Cristik