how to assert the json response array contains a substring in a string value.
I have tried this but assertion is failed response.then().body("response.content.Date", Matchers.everyItem(contains("2019-03") ));
my response body is
{
"response": {
"totalSize": 2,
"content": [
{
"requestId": " 931-f8222e",
"name": "gowtham",
"date": "2019-03-06",
"issue": "i have a cause"
},
{
"requestId": " 931-f8222e",
"name": "tharun",
"date": "2019-03-09",
"issue": "has a issue in billing"
}
]
}
}
i want to get all the records in the month(value) and assert the response showing data for given month
I found the solution. You were very close. Instead of using contains which matches full string, you can use containsString to match a substring.
Code:
response.then().body("response.content.date", Every.everyItem(Matchers.containsString("2019-03")));
Related
How can I read this type of json data like I want profession of ID:12311 in google spreadsheet?
{
"user": [
{
"id": 12311,
"name": "Deffy doof",
"profession": "Photographer"
},
{
"id": 18341,
"name": "John Smith",
"profession": "Developer"
}
]
}
Solution:
Since this is an array of objects you can reference elements using array notation, e.g., to pull "Photographer":
data.user[0].profession
Sample:
If you only know the unique ID and not the index, you can filter the array first, then get the element.
var array = data.user.filter(function b(e) { return e.id == 12311 });
console.log(array[0].profession);
References:
filter()
I've got this JSON data (not verbatim) that I get from the backend. It contains the actual data and an array of strings describing the sequence of cells to be shown:
{
"data": [
{
"name": "text",
"data": {
"text": "some text"
}
},
{
"name": "pic",
"data": {
"url": "https://somepic.jpg",
"text": "picture"
}
},
{
"name": "switcher",
"data": {
"id": 1,
"options": [
{
"id": 0,
"text": "option 1"
},
{
"id": 1,
"text": "option 2"
},
{
"id": 2,
"text": "option 3"
}
]
}
}
],
"view": [
"text",
"pic",
"switcher",
"text"
]
}
The problem is that I can't get my head around how to configure cellForRowAt: and get the right order of cells in one section. (i.e. text, pic, selector, text).
I tried a couple of things:
Looping through "view" array and switching on each individual view string to dequeue a specific cell but that doesn't seem to work since returning a cell from a switch case gives a "unexpected non-void return value in void function" error.
I was also thinking about turning a "view" array into a dictionary and then, based on keys in it, dequeue a specific cell but then again, a dictionary should have unique keys meaning that I will not have 2 "text" entries, one of them will be lost.
So, the questions is: how can I dequeue specific cells based on the array of strings? It's also important to understand that it should be done in one section. I'm feeling that it's somehow not that difficult to implement but I'm kinda lost right now. Thanks!
you need to transform your view list and data array into an array of cell contents that you can use inside the TableViewDelegate and TableViewSource method :
var cellsContents : [Int] = []
for aView in view {
var found = false
var index = 0
for aData in data {
if !found {
if let name = aData["name"] as? String {
if aView == name {
found = true
cellsContents.append(index)
continue
}
}
index = index + 1
}
}
}
Then :
number of rows : cellsContents.count
type and contents for a row : data[cellsContents[indexPath.row]]["name"] and data[cellsContents[indexPath.row]]["data"]
I am working in an application need to check a particular key value I will paste my JSON response of [[String: Any]] type. but I could not check it or else could not fetch the status key from the array.
[
{
"updated_by": <null>,
"created_at": 2018-12-26T07:28:04.000Z,
"deleted_by": <null>,
"status": Request,
"friend_id": 139,
"user_id": 141,
"id": 53,
"created_by": 141,
"deleted_at": <null>,
"is_deleted": 0,
"updated_at": <null>
}
]
I need to take "status": Request this field alone from the response and I need to check it.
For example:
if status == "Request"{
//need to do some task
} else {
//need to do some
}
I'll throw in another solution, using filter to find the desired status:
let requests = array.filter { $0["status"] as? String == "Request" }})
Where requests will contain any status == "Request" requests.
Try looping through items:
for dictionary in dict {
if let status = dictionary["status"] as? String, status == "Request" {
// Status is found
} else {
// Not found
}
}
Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character
around character 981." UserInfo={NSDebugDescription=Unescaped control
character around character 981.}
I am getting the above error in response to a request.
Below are the lines of code:
Alamofire.request(.POST, urlStr, parameters: parameter, encoding: .JSON, headers: nil).validate().responseJSON {
response in switch response.result {
case .Success(let JSON):
completionHandler(JSON as! NSDictionary)
case.Failure(let Error):
print(Error)
}
}
It gives a JSON response in Postman.
The response which is I am getting in Postman:
{
"orderdetails": {
"status_code": "200",
"status_message": "Order details",
"billingandshipping": {
"billing": {
"firstname": "first",
"lastname": "last",
"email": "aa#bbb.com",
"address": "dasdesfrew",
"city": "Rajkot",
"area": "University Road",
"pincode": "360003",
"phone": "1234567890",
"mobileno": "1234567891"
},
"shipping": {
"firstname": "first",
"lastname": "last",
"email": "aa#bbb.com",
"address": "dasdesfrew",
"city": "dasdesfrew",
"area": "dcdc",
"pincode": "360003",
"phone": "1234567890",
"mobileno": "1234567891"
}
},
"orders": [
{
"order_id": "77",
"order_date": "09-08-2016 13:05:29",
"delivery_date": "10-08-2016",
"order_items": [
{
"Sr": "1",
"product_name": "Lemon",
"gujtitle": "લીંબુ ",
"product_code": "000057",
"product_price": "108.00",
"product_qty": "2",
"unit": "1 kg.",
"product_total": "216"
}
],
"final_total": "216.00",
"shipping_cost": "0.00",
"order_total": "216.00",
"discount_type": "null",
"discount_amount": "null",
"coupon_name": "null",
"comment": "gdhdj\nfghd.g\nghj\n\n\n\n\n\n\n\n\n\n.."
}
]
}
}
As per you were told, there is a problem related to "\n".
So I suggest you can add "" which will work for you, like below:
"\n"=> "\\n"
Because this is a special character called a backspace character.
Since Swift 5, instead of manually adding another \ to your otherwise valid \n in a JSON string, you could simply declare it as a raw string literal, using this syntax:
let jsonString = #"{"comment": "gdhdj\nfghd.g\nghj\n\n\n\n\n\n\n\n\n\n.."}"#
Multiline works too:
let jsonString = #"""
{
"comment": "gdhdj\nfghd.g\nghj\n\n\n\n\n\n\n\n\n\n.."
}
"""#
While the above would compile fine if using just """ (without the #), in runtime it would throw an error in the example below with JSONSerialization, which is fixed by #""":
do {
guard let data = jsonString.data(using: .utf8) else { throw SomeError() }
let obj = try JSONSerialization.jsonObject(with: data)
print("valid!")
} catch {
print(error)
}
NSLog the NSData that you received and have a look what you find around byte 981. The thing with unescaped control characters is that they are invisible, so you can't see them in an NSString, but you'll see them in the NSData.
If your data has length 981 bytes or very close then there's a chance that your code processed incomplete JSON data which will almost always fail; that's something you need to fix. If there is a control character between some items (say between two array elements) then this might be a bug in the server code.
I spent some time to figure out what 49546 was.
If your issue is Unescaped control character around character 49546, replace \t with \\\t.
To be sure (as people make foul copy/paste...), I build my object safe:
...
private final func fillWith(
id: Int,
name: String?
) {
self.id = id
self.productName = name?.replacingOccurrences(of: "\t", with: "")
self.productName = self.productName?.replacingOccurrences(of: "\n", with: "")
So no problem when sending up.
Here is my Json
{
"id": "63",
"name": "Magnet",
"price": "₹1250",
"description": "",
"image": [
"catalog/IMG-20150119-WA0012_azw1e3ge.jpg",
"catalog/IMG-20150119-WA0029_6mr3ndda.jpg",
"catalog/IMG-20150119-WA0028_ooc2ea52.jpg",
"catalog/IMG-20150119-WA0026_4wjz5882.jpg",
"catalog/IMG-20150119-WA0024_e38xvczi.jpg",
"catalog/IMG-20150119-WA0020_vyzhfkvf.jpg",
"catalog/IMG-20150119-WA0018_u686bmde.jpg",
"catalog/IMG-20150119-WA0016_c8ffp19i.jpg"
],
"thumb_image": [
"cache/catalog/IMG-20150119-WA0012_azw1e3ge-300x412.jpg",
"cache/catalog/IMG-20150119-WA0029_6mr3ndda-300x412.jpg",
"cache/catalog/IMG-20150119-WA0028_ooc2ea52-300x412.jpg",
"cache/catalog/IMG-20150119-WA0026_4wjz5882-300x412.jpg",
"cache/catalog/IMG-20150119-WA0024_e38xvczi-300x412.jpg",
"cache/catalog/IMG-20150119-WA0020_vyzhfkvf-300x412.jpg",
"cache/catalog/IMG-20150119-WA0018_u686bmde-300x412.jpg",
"cache/catalog/IMG-20150119-WA0016_c8ffp19i-300x412.jpg"
],
"specifications": [
{
"Fabrics": [
"Pure chiffon straight cut suits 48" length"
]
},
{
"MOQ": [
"Minimum 10"
]
}
]
}
In above json string the "specification" arraylist has dynamic number of key and each key has dynamic number of values
So how can parse this? Please help if anyone knows this...
Thanks in advance
There are multiple ways to do parsing. In your case specifications should be an array, so you'll be able to loop on each items.
You might want to :
Create your own JSON parse class / methods ;
Use an existing library to parse JSON.
For the second option, you can give a look at the following :
https://github.com/Wolg/awesome-swift#jsonxml-manipulation
var yourJson = data as? NSDictionary
if let id = yourJson.valueForKey("id") as String
{
//save your id from json
}
if let name = yourJson.valueForKey("name") as String
{
//save your name
}
...
if let images = yourJson.valueForKey("image") as NSArray
{
for im in images
{
//save image
}
//the same for all othe images
}
... And so on...
You should also watch some tutorials, to understand the basics of JSON parsing..
https://www.youtube.com/watch?v=MtcscjMxxq4