I am using Rest Assured for API testing, how do I send array objects in a POST? For a plain string I know I can do something like this
JSONObject json = new JSONObject();
json.put("firstname", "John"));
json.put("lastname", "James");
request.body(json.toJSONString());
request.post("/my/post/url/end/point");
How do I send an object like this using the JSONObject and Rest Assured?
{
"price": "234",
"phoneNumber": "09022334422",
"owner": [{
"digits": "1122334455",
"myname": "Abisoye Haminat",
"code": "058",
"default": "true"
}]
}
To send an array, you can use JSONArray:
JSONObject jsonObjectToPost = new JSONObject();
JSONArray array = new JSONArray();
JSONObject arrayItem = new JSONObject();
arrayItem.put("code","058");
arrayItem.put("default", "true");
array.put(arrayItem.toString());
jsonObjectToPost.put("owner", array.toString())
Related
I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}
How can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));
I want to make an array of product objects from a json file which is currently a String.
{
"invoice": {
"products": {
"product": [
{
"name": "Food",
"price": "5.00"
},
{
"name": "Drink",
"price": "2.00"
}
]
},
"total": "7.00"
}
}
...
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("product");
the line below give me: java.lang.NullPointerException
for(JsonElement element: jsonArray) {
//do stuff
System.out.println(element);
}
some code goes here...
product = new Product(name, price);
List<Product> products = new ArrayList<Product>();
products.add(product);
You have to traverse the whole JSON string to get to the "product" part.
JsonArray jsonArray = jsonObject.get("invoice").getAsJsonObject().get("products").getAsJsonObject().get("product").getAsJsonArray();
I would recommend that you create a custom deserializer as described in the second answer to this question: How do I write a custom JSON deserializer for Gson? This will make it a lot cleaner, and let you handle improper JSON and make it easier in case your JSON ever changes.
I think you can use Gson library for this
You can find the project and the documentation at : https://github.com/google/gson/blob/master/README.md
try
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject invoice = parser.parse(jsonString).getAsJsonObject();
JsonObject products = invoice.getAsJsonObject("products");
JsonArray jsonArray = products.getAsJsonArray("product");
In using Facebook messenger to send structured messages using generic template based on official documentation here. 'm using Java to construct the JSON object. Whenever I send the JSON to Facebook I get a response "400- bad request"I. I tried comparing using an online tool, the java generated JSON to that provided in the documentation and apart from the variable names nothing else is different. Can't understand where I'm going wrong in constructing the JSON.
JSON Generated from Java Code..
{
"message": {
"attachment": {
"payload": {
"elements": [
{
"buttons": [
{
"title": "show website",
"type": "web_url",
"url": "https://google.com"
},
{
"payload": "sample payload",
"title": "Hi There",
"type": "postback"
}
],
"default_action": {
"fallback_url": "https://www.google.com/",
"messenger_extensions": true,
"type": "web_url",
"url": "https://www.google.com/",
"webview_height_ratio": "tall"
},
"image_url": "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png",
"subtitle": "Sample Sub Title",
"title": "Sample Title"
}
],
"template_type": "generic"
},
"type": "template"
}
},
"recipient": {
"id": "988459377921053"
}
}
Corresponding Java Code..
JSONObject root1 = new JSONObject();
JSONObject c01 = new JSONObject();
JSONObject c11 = new JSONObject();
JSONObject attachment = new JSONObject();
JSONObject payload = new JSONObject();
JSONArray arrayButton= new JSONArray();
JSONArray arrayelements= new JSONArray();
JSONObject elementsObj = new JSONObject();
JSONObject defaultAction = new JSONObject();
JSONObject buttons1 = new JSONObject();
JSONObject buttons2 = new JSONObject();
root1.put("recipient", c01);
c01.put("id", userId);
root1.put("message", c11);
c11.put("attachment", attachment);
attachment.put("type", "template");
attachment.put("payload", payload);
payload.put("template_type", "generic");
payload.put("elements", arrayelements);
arrayelements.put(elementsObj);
elementsObj.put("title", "Sample Title");
elementsObj.put("image_url", "https://s3-ap-southeast-1.amazonaws.com/primary-4495.png");
elementsObj.put("subtitle", "Sample Sub Title");
elementsObj.put("default_action", defaultAction);
defaultAction.put("type", "web_url");
defaultAction.put("url", "https://www.google.com/");
defaultAction.put("messenger_extensions", true);
defaultAction.put("webview_height_ratio", "tall");
defaultAction.put("fallback_url", "https://www.google.com/");
buttons1.put("type", "web_url");
buttons1.put("url", "https://google.com");
buttons1.put("title", "show website");
arrayButton.put(buttons1);
buttons2.put("type", "postback");
buttons2.put("title", "Hi There");
buttons2.put("payload", "sample payload");
arrayButton.put(buttons2);
elementsObj.put("buttons", arrayButton);
As you can see when comparing the above json with the sample one provided in the official documentation, only the order of elements is different. Stuck on this problem for the past 2 days..Please help..
Found my mistake!!
Whenever we try to use messenger_extensions property we have to whitelist the domain name otherwise messenger platform will return 400 error. Since I didn't need messenger_extensions property, I removed the entire default action section and now messenger API is returning 200 code. In case you want to whitelist your domain you can follow the below link.
https://developers.facebook.com/docs/messenger-platform/thread-settings/domain-whitelisting
how can I create a JSON Object like the following, in Java using JSONObject ?
{
"employees": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
],
"manager": [
{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}
]
}
I've found a lot of example, but not my exactly JSONArray string.
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Small reusable method can be written for creating person json object to avoid duplicate code
JSONObject getPerson(String firstName, String lastName){
JSONObject person = new JSONObject();
person .put("firstName", firstName);
person .put("lastName", lastName);
return person ;
}
public JSONObject getJsonResponse(){
JSONArray employees = new JSONArray();
employees.put(getPerson("John","Doe"));
employees.put(getPerson("Anna","Smith"));
employees.put(getPerson("Peter","Jones"));
JSONArray managers = new JSONArray();
managers.put(getPerson("John","Doe"));
managers.put(getPerson("Anna","Smith"));
managers.put(getPerson("Peter","Jones"));
JSONObject response= new JSONObject();
response.put("employees", employees );
response.put("manager", managers );
return response;
}
Please try this ... hope it helps
JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();
jsonObj1=new JSONObject();
jsonObj2=new JSONObject();
array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);
Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;