2
votes

I am a java, json, rest assured newbie and trying to work and learn how to test a rest api. I have an array returned as a rest assured response:

 Response response = given(getProjectInfoRequest).get();
 response.asString(); 

{
    "options": [
        {
            "text": "111",
            "label": "ABC"
        },
        {
            "text": "222",
            "label": "DEF"
        },
        {
            "text": "333",
            "label": "GHI"
        }
    ]
}

and I want to extract the value of text say for label value as "DEF", how I can do that?

Please note I have done below so far after reading through so many posts:

1. Options[] options = given(getProjectInfoRequest).when().get().as(Options[].class);
this was giving me exception :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

then I tried below:
2. Options options = gson.fromJson(response.asString(), Options.getClass());
this at least resolved the above issue.
    public class Options {
    public String getLabel() {
        return label
    }

    public void setLabel(String label) {
        this.label = label
    }

    public String getValue() {
        return value
    }

    public void setValue(String value) {
        this.value = value
    }
    public String label;
    public String value;
} 

From this point I am not sure how I can iterate through the array of text and values to extract what I need, please can you guys provide your inputs?

Please pardon my ignorance for asking such a basic question. Please also suggest me a good source/way to learn this too.

Thanks in advance!

1

1 Answers

3
votes

U can use Gson - This is a Java library that can be used to convert Java Objects into their JSON representation.

JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse(response.asString());

for (Map.Entry<String,JsonElement> entry : o.entrySet()) {
    JsonArray array = entry.getValue().getAsJsonArray();
    for (JsonElement elementJSON : array) {
        [...]
    }
}