user5282677
user5282677

Reputation:

How to read data from an API which returns data in json in selenium webdriver?

Basically i am firing a set of APIs using GET call which returns data in json, and i want to print only specific String like hostid as mentioned in below json snippet.

  "hostId" : 286,
  "parentSectionName" : "adadfr",
  "rank" : 86096.0,
  "activationStatus" : "ACTIVE",
  "overrideLinkProp" : 0,

Upvotes: 0

Views: 2573

Answers (2)

baadnews
baadnews

Reputation: 128

In java you can use JsonPath:

String jsonToDecode =   "{" +
         " \"hostId\" : 286,\n" +
            "  \"parentSectionName\" : \"adadfr\",\n" +
            "  \"rank\" : 86096.0,\n" +
            "  \"activationStatus\" : \"ACTIVE\",\n" +
            "  \"overrideLinkProp\" : 0,"+
            "}";
System.out.println(JsonPath.from(jsonToDecode).getString("hostId"));

Upvotes: 0

Dan Ionescu
Dan Ionescu

Reputation: 3423

Assuming that your json looks like this:

        String jsonToDecode =   "{" +
         " \"hostId\" : 286,\n" +
            "  \"parentSectionName\" : \"adadfr\",\n" +
            "  \"rank\" : 86096.0,\n" +
            "  \"activationStatus\" : \"ACTIVE\",\n" +
            "  \"overrideLinkProp\" : 0,"+
            "}";

You can decode it using "com.googlecode.json-simple" package like so:

    JSONParser parser = new JSONParser();
    Object parsedJson = new Object();
    try {
        parsedJson  = parser.parse(jsonToDecode);
    } catch (ParseException e) {
        //do something when json parsing fails
    }
    JSONObject jsonObject = (JSONObject) parsedJson;
    String name = (String) jsonObject.get("parentSectionName");
    System.out.print(name); // will output adadfr

Upvotes: 0

Related Questions