Hire QA – Specialized in QA Recruitment, Technical Interviews and Testing Solutions

Retrieve a field value from JSON Object

Category: Rest Assured

To retrieve a field value we need to use get(String fieldName). If passed field name does not have a value or if there is no field with such name, null is returned. It returns a JsonNode. To get value in actual data types we need to use respective methods like asText() to get value as String or asBoolean() to get value as boolean. Be careful when field value is another ObjectNode.

//defining a JSON string  
String s="{\"name\":\"Phani\",\"Salary\":50000.0}";    
Object obj=JSONValue.parse(s);    
//creating an object of JSONObject class and casting the object into JSONObject type  
JSONObject jsonObject = (JSONObject) obj;    
//getting values form the JSONObject and casting that values into corresponding types  
String name = jsonObject.get("name").asText();    
double salary = jsonObject.get("Salary").asDouble();    
//printing the values   
System.out.println("Name: "+name);  
System.out.println("Salary: "+salary);  

Leave a Reply

Your email address will not be published. Required fields are marked *