I am trying to pass following parameters to request body but its not working :
{
"Start": 0,
"Limit": 10,
"SysID": 632;
"ResultScope": "Enrolled",
"SearchParams":
[
{"Field":"ID", "Weight": 1, "Value": ["1234567"], "Operation": "Active", "Enabled": true}
]
}
What i tried:
var test = request.AddBody(new Search { Start = 0, Limit = 10, SysId = 632, ResultScope = "Enrolled", SearchParams = new List<Object> { "ID", 1, 1234567, "Active”, "true" } });
but its not working. I am getting target parametercount exception when i am trying to add it to request as Addobject after seralization
You might want to read the docs.
request.AddJsonBody(
new Search {
Start = 0,
Limit = 10,
SysId = 632,
ResultScope = "Enrolled",
SearchParams = new List<Object> { "ID", 1, 1234567, "Active”, "true" }
});
var response = await client.GetAsync<WhateverYouWantBack>(request);
Related
This is the response body of post method
"body":
{
"id": 538,
"Fname": "abc",
"Lname": "Xyz",
"Type": {
"Type": "tryrtyr",
"createdBy": "ytyryr",
"createdDate": "2022-07-22T09:24:37.616+00:00",
"lastModifiedBy": "rtyryry",
"lastModifiedDate": "2022-07-22T09:24:37.616+00:00"
}
}
I tried to fetch the Id value but it is showing null value.
Fname, Lname are passing from excel file.
String jsonString = response.asString();
jsonString = response.asString();
List<Map<String, Object>> body = JsonPath.from(jsonString).get("");
Object Id = null;
for (Map<String, Object> item: body) {
if (item.get("Fname").toString().equals(Fname) &&
item.get("Lname").toString().equals(Lname)); {
Id = Integer.parseInt(item.get("id").toString());
}
}
System.out.println(Id);
Since the body is json object, not array, so you don't need a List here. I think you just need.
int id = response.jsonpath().getInt("id");
I have a method that returns a Json object from a query using the FOR JOSN PATH approach.
Example:
SELECT State, COUNT(*) AS Items
FROM dbo.States
WHERE SomeFilterColumn = #FilterParam
GROUP BY State
FOR JSON PATH
This returns
[
{
"State": "Pending",
"Items": 23
},
{
"State": "Finished",
"Items", 7736
}
]
I also have a function in Powershell that returns the result. However I have issues how it is returned.
function Get-Json-From-Query {
param(
[Int32]$filterParam
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
...
$SqlCmd = $SqlConnection.CreateCommand();
$SqlCmd.CommandText = $Query #The query shown above
$SqlCmd.Parameters.Add("#FilterParam", $filterParam);
$SqlCmd.ExecuteScalar()
}
However I do not know how to get the result of my query properly added to a JSON value.
I tried many things like:
#{
States = (Get-Json-From-Query -filterParam 1234)
}
However this gives me also the param information which I do not want:
Expecting
{ "States": [... The Array show above ... ] }
Actual
{
"States": [
{
"CompareInfo": 0,
"XmlSchemaCollectionDatabase": "",
"XmlSchemaCollectionOwningSchema": "",
"XmlSchemaCollectionName": "",
"ForceColumnEncryption": false,
"DbType": 11,
"LocaleId": 0,
"ParameterName": "#FilterParam",
"Precision": 0,
"Scale": 0,
"SqlDbType": 8,
"SqlValue": "1234",
"UdtTypeName": "",
"TypeName": "",
"Value": 1234,
"Direction": 1,
"IsNullable": false,
"Offset": 0,
"Size": 0,
"SourceColumn": "",
"SourceColumnNullMapping": false,
"SourceVersion": 512
},
"[{\"State\":\"Pending\",\"Items\":23},{\"State\":\"Finished\",\"Items\":7763}]"
]
}
How do I get the right data in my Json object?
{
"a": {
"b": 1,
"c": 0
},
"values": [
{
"d": "WERTY",
"e": "details",
"f": [
{
"addressId": "vvvv",
"address": "ffff"
}
]
},
{
"d": "ZXCVB",
"e": "details"
},
{
"d": "ASDFG",
"e": "details",
"f": [
{
"addressId": "vvvv",
"address": "xxxx"
}
]
}
]
}
After getting the response from restassured, I am trying to fetch the values of a particular key with JsonPath.
I am using:
responseBody.jsonPath().getList("values.f.address)
This is returning me a list - ["ffff","xxxx"]
I want to get - ["ffff",null,"xxxx"]
Is it possible to achieve this with Karate?
JsonPath = values[0].f[0].address
If you are using validatableResonse then you can use:
String res_str = Response.extract().jsonPath().getString("values[0].f[0].address");
The response should be of ValidatableResponse type.
It won't return you null for that absent item, because field address is actually not present in the response body.
You can do it checking whether the f key is available in each object of values array;
If it is available -> add the value of address in each object in f array, to a String list
If it is not available -> add null to the same String list.
I create a org.json.JSONObject from io.restassured.response.Response.
Response response = given()
.when()
.get(url)
.then()
.extract()
.response();
List<String> addressList = new ArrayList<>();
JSONObject responseObject = new org.json.JSONObject(response.body().asString());
JSONArray jsonArray = responseObject.getJSONArray("values");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.keySet().contains("f")) {
JSONArray fObjectArray = jsonObject.getJSONArray("f");
for (int j = 0; j < fObjectArray.length(); j++) {
addressList.add(fObjectArray.getJSONObject(j).get("address").toString());
}
} else {
addressList.add(null);
}
}
System.out.println(addressList.toString());
This will print the following result;
[ffff, null, xxxx]
I called the flight offer search API. It returned 8 flight offers. I then picked the first offer and called the flight offer price API. I got this error
{ "errors": [ { "code": 38196, "title": "Resource not found", "detail": "The targeted resource doesn't exist", "status": 404 } ] }
Can anyone let me know what is wrong with my code please? Thanks in advance.
confirmFlightOffer = #"{
""data"": {
""type"": ""flight-offers-pricing"",
""flightOffers"": [
{
""type"": ""flight-offer"",
""id"": ""1"",
""source"": ""GDS"",
""instantTicketingRequired"": false,
""nonHomogeneous"": false,
""oneWay"": false,
""lastTicketingDate"": ""2020-06-06"",
""numberOfBookableSeats"": 9,
""itineraries"": [
{
""duration"": ""PT1H35M"",
""segments"": [
{
""departure"": {
""iataCode"": ""SYD"",
""terminal"": ""2"",
""at"": ""2020-06-14T13:20:00""
},
""arrival"": {
""iataCode"": ""MEL"",
""terminal"": ""4"",
""at"": ""2020-06-14T14:55:00""
},
""carrierCode"": ""JQ"",
""number"": ""513"",
""aircraft"": { ""code"": ""320"" },
""operating"": { ""carrierCode"": ""JQ"" },
""duration"": ""PT1H35M"",
""id"": ""22"",
""numberOfStops"": 0,
""blacklistedInEU"": false
}
]
}
],
""price"": {
""currency"": ""AUD"",
""total"": ""140.74"",
""base"": ""102.75"",
""fees"": [
{
""amount"": ""0.00"",
""type"": ""SUPPLIER""
},
{
""amount"": ""0.00"",
""type"": ""TICKETING""
}
],
""grandTotal"": ""140.74""
},
""pricingOptions"": {
""fareType"": [ ""PUBLISHED"" ],
""includedCheckedBagsOnly"": true
},
""validatingAirlineCodes"": [ ""HR"" ],
""travelerPricings"": [
{
""travelerId"": ""1"",
""fareOption"": ""STANDARD"",
""travelerType"": ""ADULT"",
""price"": {
""currency"": ""AUD"",
""total"": ""140.74"",
""base"": ""102.75""
},
""fareDetailsBySegment"": [
{
""segmentId"": ""22"",
""cabin"": ""ECONOMY"",
""fareBasis"": ""HLOW"",
""class"": ""H"",
""includedCheckedBags"": {
""weight"": 20,
""weightUnit"": ""KG""
}
}
]
}
]
}
]
}
}";
var client = new RestClient(_apiUrl);
client.Timeout = -1;
var request = new RestRequest("/v1/shopping/flight-offers/pricing", Method.POST);
request.AddHeader("Authorization", $"Bearer {_token}");
request.AddHeader("content-type", "application/json");
request.AddParameter("application/json", confirmFlightOffer, ParameterType.RequestBody);
var response = client.Execute<ConfirmFlightOfferResponse>(request);
I found the problem
This works
var client = new RestClient(_apiUrl + "/v1/shopping/flight-offers/pricing");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
but this doesn't
var client = new RestClient(_apiUrl);
client.Timeout = -1;
var request = new RestRequest("/v1/shopping/flight-offers/pricing",Method.POST);
Don't know why.
I have a order screen where the placed orders and the items that are placed for each order is displayed. I have used a for loop to fetch the orders from the api but in the order json response it also has items parameter inside which there are multiple items. I am not able to figure out how to place another loop in the code to fetch the items list. So please help me with it...
Thank you..
my json response
[
{
"id": 1453,
"total": "407.00",
"line_items": [
{
"id": 34,
"name": "Aloo Chaat Salad",
"product_id": 931,
"quantity": 1,
"total": "90.00",
},
{
"id": 35,
"name": "Aloo Jeera",
"product_id": 1020,
"quantity": 1,
"total": "140.00",
},
{
"id": 36,
"name": "Banana Shake",
"product_id": 963,
"quantity": 1,
"tax_class": "",
"total": "140.00",
}
],
}
]
myModel.dart
class OrderListModel {
final int id;
final String total;
Map line_items = {};
OrderListModel(this.id, this.total, this.line_items);
}
my code for fetching the data
List<OrderListModel> myAllDatas = [];
Future getDatas() async {
String basicAuth = 'Basic ' +
base64.encode(
utf8.encode('${GlobalVar.consumerKey}:${GlobalVar.secretKey}'));
var response = await http
.get("${GlobalVar.url}wp-json/wc/v2/orders?customer=6", headers: {
'Authorization': basicAuth,
'Accept': 'application/json',
});
if (response.statusCode == 200) {
String responseBody = response.body;
var jsonBody = json.decode(responseBody);
for (var data in jsonBody) // loop for fetching the orders
{
myAllDatas.add(new OrderListModel(data['id'], data['total'],
data['line_items'])); // how to place a loop so that i can fetch the items
inside the line_items parameter too?
}
setState(() {});
} else {
print(response.statusCode);
print(response.body);
}
}
when I fetch the items of line_items i just want to fetch their names and seperate them by commas in a row.
Use for loop like this -
for (var data in body) {
List items = data["line_items"];
for (int i = 0; i < items.length; i++) {
int id = items[i]["id"];
String name = items[i]["name"];
}
}