How to Parse Json String Read Value for a Key in Java

How to parse JSON responses in Katalon Studio

About the author

Marek Melocik is currently working as Examination Automation Engineer in Brno, Czechia. He has been working in the QA industry since 2014.

Meet Marek at world wide web.linkedin.com/in/marek-melocik

Many people in the Katalon forum have asked virtually retrieving data from JSON responses and parsing the JSON format in Katalon Studio. In this postal service, I will show a simple mode on how to practice then.

A JSON response instance

Suppose we accept the post-obit JSON response, and we want to parse and retrieve its data:

                              {                "card"                :                {                "id"                :                "file"                ,                "tools"                :                {                "actions"                :                [                {                "id"                :                "new"                ,                "title"                :                "New file"                },                {                "id"                :                "open"                ,                "title"                :                "Open File"                },                {                "id"                :                "close"                ,                "title"                :                "Close File"                }                ],                "errors"                :                []                }}}                          

JsonSlurper

We use this Slap-up helper class to parse JSON strings. We need to create a new example of JsonSlurper and call the JsonSlurper.parseText method. Sample code:

                              import                groovy.json.JsonSlurper                                String                jsonString                =                '''{"bill of fare": { "id": "file", "tools": { "deportment": [ {"id": "new", "title": "New File"}, {"id": "open", "title": "Open File"}, {"id": "close", "title": "Shut File"} ], "errors": [] }}}'''                JsonSlurper                slurper                =                new                JsonSlurper                ()                Map                parsedJson                =                slurper                .                parseText                (                jsonString                )                          

The parsed JSON response is now stored in a variable called parsedJson (in our case, it is the Map data structure, but sometimes it may exist something else).

JsonSlurper too provides a couple of JsonSlurper.parse overloading methods which can be used if your JSON input is File, Reader, InputStream, URL other than Cord. For further information, please refer to the JsonSlurper documentation.

Get a key value

Let's say y'all desire to get a value of id from the JSON response in a higher place. JSON is a structured document, so you tin go any element using its absolute path. Encounter this instance:

                              String                idValue                =                parsedJson                .                card                .                id                                String                idValue2                =                parsedJson                .                become                (                "card"                ).                get                (                "id"                )                          

As y'all can see,  there are two ways how to get it. I is to access Map objects by using the dot notation (.). The other is to employ get methods from Map, List and Set as yous do in Java.

Basically, the parsedJson variable is a type of Map<String, Map<Object, Object>>. Then, to get inner Map, you call parsedJson.get("menu") – as "menu" is the String primal. This method returns the inner Map, on which yous can telephone call other become methods until you reach your fundamental.

Verify if a key is present in JSON

If you lot want to verify if a selected key is present in a JSON response, you can use the like lawmaking as beneath:

                              import                com.kms.katalon.core.util.KeywordUtil                                String                getSelectedKey                =                parsedJson                .                menu                .                id                                if                (                getSelectedKey                ==                zilch                )                {                KeywordUtil                .                markFailed                (                "Primal is not nowadays"                )                }                It                is                a                simple                check                for                zero                                if                the                given                primal                is                non                establish                ,                null                is                returned                .                Only                there                is                1                special                case                when                this                code                won                '                t                work                ,                that                is                ,                if                key                "id"                has                value                zip                in                your                JSON                .                For                such                cases                y'all                should                utilise                more                robust                code:                boolean                isKeyPresent                =                parsedJson                .                become                (                "card"                ).                keySet                ().                contains                (                "id"                )                                if                (!                isKeyPresent                )                {                KeywordUtil                .                markFailed                (                "Key is not nowadays"                )                }                          

Yous become all keys from the "carte" object and and then check if information technology contains the central you look for.

Get an array chemical element

Your JSON response may also contain arrays. Like whatever array in Java or Groovy, you can access an array chemical element using arrayName[index].

For example, we tin can get the "title" value of the starting time object in the "actions" array as beneath

                              String                idValue                =                parsedJson                .                bill of fare                .                tools                .                actions                [                0                ].                championship                                Cord                idValue2                =                parsedJson                .                get                (                "menu"                ).                get                (                "tools"                ).                get                (                "actions"                ).                get                (                0                ).                get                (                "championship"                )                          

In this case, we admission the detail with the index of 0, the first item in the assortment (the index is zero-based).

Get an assortment chemical element based on some condition

A more usual case is when you want to get the exact array element based on some specific status. For example, you lot get the "championship" value of an object whose "id" is "Open". You tin do this as below:

                              def                array1                =                parsedJson                .                menu                .                tools                .                actions                                String                onlickValue1                =                ""                                for                (                def                member                :                array1                )                {                if                (                member                .                id                ==                'Open'                )                {                onlickValue1                =                fellow member                .                championship                break                }                }                          

I used the for-each loop in this case. This loop checks every item in the array array1 until the condition is met. If and so, onlickValue1 is assigned to the particular'due south championship.

JSON data types

The JSON format supports a few information types such as String, number, Boolean, and nada. If you are not sure what the information type is, you tin only utilize the keyword def .

                              def                myVar                =                'get value from json hither'                .                          

A rule of thumb is that a String value is enclosed in quotes, numbers unquoted (floating betoken may exist nowadays as well) and Boolean true or imitation. But initializing a variable using def is always a skilful choice when yous are non sure most its type.

Determination

This tutorial offers a few basic all-time practices for working with JSON strings in Katalon Studio. JSON is the near common format returned from API/Web Services. When yous perform API testing , you lot likely have to deal with JSON responses. Hopefully, these bones best practices are useful for your API testing.

Rest API Request Katalon Studio

Read more:

  • Create your offset API test with Katalon Studio
  • Create Rest API requests manually
  • Tiptop 50+ Spider web API Testing Interview Questions

Feedback

ringgoldfarome.blogspot.com

Source: https://docs.katalon.com/katalon-studio/docs/parse_json_responses.html

0 Response to "How to Parse Json String Read Value for a Key in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel