how to find the number of response object in json - json

I have a JSON response to validate. I am writing a test secario where I want to assert if the response contains the number of objects or not. JSON response:
{
"Result": {
"resultCode": "1000",
},
"ResultClient": {
"responseCode": null,
"statusCode": null
},
"creditCard": {
"number": null
}
}
I want to assert that the response has 3 objects. How to do that? The response obj dosn't have size() or count() so I am unable to understand the path to the solution.I am writting my tests in rest-assured .
TestResponse testResponse = given()
.contentType("application/json; charset=UTF-8")
.body(cTestRequest)
.when()
.post(uri)
.as(TestResponse.class);
now how to assert the json contains the 3 obj and the parameters inside the objs?

You can do something like this:
when().
get("/x").
then().
body("keySet().size()", is(3));
The reason is that the JSON object is treated as Groovy Map so you can invoke functions on it. keySet() returns all keys as a Set and size() returns the size of this Set.

Related

How to pass multiple json objects of array to post request in jmeter using groovy script

POST API is triggering fine and taking only first json object from array and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially using JMeter and Groovy.
json payload : Below is the sample json payload
[
{
"person": "abc",
"Id": "123"},
{
"person": "adfg",
"Id": "12883"},
{
"person": "adf",
"Id": "125"}
]
Groovy code : Reading data from json file which includes multiple json objects and send it to post request in jmeter.
try
{
JsonSlurper jsonSlurper=new JsonSlurper();
def jsonPayload = jsonSlurper.parse(new File('PAYLOAD.json'))
String inputData = new groovy.json.JsonBuilder(jsonPayload)
JsonElement root = new JsonParser().parse(inputData);
JsonArray jsonArray = root.getAsJsonArray();
log.info("jsonArray:"+jsonArray);
if(jsonArray != null && !jsonArray.isEmpty())
{
jsonArray.each{paylodData ->
println paylodData
log.info("post data:"+paylodData);
vars.putObject("payloads", paylodData.toString())
log.info('Generated body: ' + vars.getObject('payloads'))
}
}
}catch (FileNotFoundException fe) {
log.info("Error: Please Check the file path");
}
JMeter Test : Triggering same API with multiple payloads
using below variable in post request body
${payloads}
NOTE : API is triggering fine and taking only first json object and rest of the json objects are not passing. I need to trigger API with multiple json payloads sequentially.
What are you trying to achieve?
You have a foreach loop which iterates the JSON Array and writes the inner object value into a payloads JMeter Variable
The point is that each iteration of the foreach loop overwrites the previous value in the variable so you will always get the last value.
You either need to replace jsonArray.each with jsonArray.eachWithIndex and store each array member into a separate variable like:
payload_0 = first array member
payload_1 = second array member
etc.
or transform the response into another format, but here I cannot suggest anything because I don't know what is the expected one.
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy: What Is Groovy Used For?

What might cause (JSON ERROR: no value for)?

I have written some code in Kotlin that should retrieve some data for a dictionary app using the JSON Request Object. I can see that the call is made successfully. The website receiving the call shows the data being sent back but I'm not getting anything back in the results object. Logcat is showing this error (E/JSONĀ ERROR: No value for results). I'm not sure where I'm going wrong in extracting the results. Can someone point me in the right direction?
val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
{ response ->
try {
val resultsObj = response.getJSONObject("results")
val result: JSONObject = response.getJSONObject("result")
val term = result.getString("term")
val definition = result.getString("definition")
val partOfSpeech = result.getString("partOfSpeech")
val example = result.getString("example")
} catch (ex: JSONException) {
Log.e("JSON ERROR", ex.message!!)
}
},
{ error: VolleyError? -> error?.printStackTrace() })
The JSON
{
"results": {
"result": {
"term": "consistent, uniform",
"definition": "the same throughout in structure or composition",
"partofspeech": "adj",
"example": "bituminous coal is often treated as a
consistent and homogeneous product"
}
}
}
Have you checked the json format? Json Formatter
Here with this code it is valid. You had his character end line in the wrong place.
{
"results":{
"result":{
"term":"consistent, uniform",
"definition":"the same throughout in structure or composition",
"partofspeech":"adj",
"example":"bituminous coal is often treated as a consistent and homogeneous product"
}
}
}

How do I PUT and GET JSON object of ANY format in a Spring Boot REST API using MySQL?

I need to be able to PUT a JSON data from POSTMAN, with no fixed format, store it in database(in MYSQL preferably with datatype: JSON) and then send a GET request to get the same value back. The data can be uniquely identified by an id that I'll be sending as a path variable.
I cannot define an entity class as the JSON will have no fixed format. How do I proceed?
#PutMapping("/sample/{sampleNo}")
public ResponseEntity<Object> addSampleData(
#ApiParam("Sampleto PUT") #PathVariable Long sampleNo, #RequestBody String sampleBody) {
if (sampleBody!= null) {
sampleService.save(new Sample(sampleNo, sampleBody));
return new ResponseEntity<>(HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}
Not sure how to proceed with the "save" functionality so that the data is stored as a JSON object, because even if I've used datatype JSON n mySQL, GET returns a string with "\".
{
"sampleNo": 1,
"sampleData": "{\"sample\": \"test\", \"sampleNo\": \"20\"}"
}
Example: PUT request body
{
"field1": "test",
"field2": 20
}
GET response body expected
{
"field1": "test",
"field2": 20
}
P.S: I don't need to process the data, so it doesn't matter how I store it, I just need to be able to GET it back in the same format(JSON) it arrived(in the PUT req).
sampleData is returned as JSON String, so it is reasonable to include escape sequence \":
This is a valid JSON String:
String json = "{\"sample\": \"test\", \"sampleNo\": \"20\"}";
This does not compile:
String invalidJson = "{"sample": "test", "sampleNo": "20"}";
Solution:
In order to have the expected response, you have to map your MySQL JSON column into an Object.
There are several ways to achieve this, take a look at a solution here. It maps JSON column into a Map<String, Object>.

Accessing JSON response

I am storing the response of a REST Get request and trying to access as below,
final JSONObject receivedItem = new JSONObject(response.readEntity(String.class));
This is the sample response,
[
{
"timeStamp": 1511136000000,
"contextKeys": [
{
"tKey": "Test1",
"contextKey": "Location",
"contextValue": "San Jose",
"eCount": 3
},
{
"tKey": "Test1",
"contextKey": "Name",
"contextValue": "User1",
"eCount": 3
}
}
]
And i am getting the below error,
org.json.JSONException: A JSONObject text must begin with '{' at character 1
at org.json.JSONTokener.syntaxError(JSONTokener.java:496)
at org.json.JSONObject.<init>(JSONObject.java:180)
at org.json.JSONObject.<init>(JSONObject.java:403)
Any clues ?
Thanks
As Rajkumar pointed out, in your example there is a missing close bracket - but this may just be a simple typing error.
The actual error message is saying A JSONObject text must begin with '{' which is because JSON objects are exactly that, objects. You need to use a JSONArray to parse your example JSON as follows:
final JSONArray receivedItem = new JSONArray(response.readEntity(String.class));
This may change some of your other code to handle this as an array vs an object.
If your problem is with storing and accessing json response try this response instead;
I am presuming that you are using javascript; Anyways, core idea is the same;
var jsonStorage;
$.getJSON('your url',(json) => {
jsonStorage = json;
});
console.log(jsonStorage) //your jsonresponse is now available here;

Grails: Parsing through JSON String using JSONArray/JSONObject

I have the below JSON string coming in as a request parameter into my grails controller.
{
"loginName":"user1",
"timesheetList":
[
{
"periodBegin":"2014/10/12",
"periodEnd":"2014/10/18",
"timesheetRows":[
{
"task":"Cleaning",
"description":"cleaning description",
"paycode":"payCode1"
},
{
"task":"painting",
"activityDescription":"painting description",
"paycode":"payCode2"
}
]
}
],
"overallStatus":"SUCCESS"
}
As you can see, the timesheetList might have multiple elements in it. In this ( above ) case, we have only one. So, I expect it to behave like an Array/List.
Then I had the below code to parse through it:
String saveJSON // This holds the above JSON string.
def jsonObject = grails.converters.JSON.parse(saveJSON) // No problem here. Returns a JSONObject. I checked the class type.
def jsonArray = jsonArray.timesheetList // No problem here. Returns a JSONArray. I checked the class type.
println "*** Size of jsonArray1: " + jsonArray1.size() // Returns size 1. It seemed fine as the above JSON string had only one timesheet in timesheetList
def timesheet1 = jsonArray[1] // This throws the JSONException, JSONArray[1] not found. I tried jsonArray.getJSONObject(1) and that throws the same exception.
Basically, I am looking to seamlessly iterate through the JSON string now. Any help?
1st off to simplify your code, use request.JSON. Then request.JSON.list[ 0 ] should be working