Cannot convert value of type 'NSData' to type 'Date' in coercion in json work? [closed] - swift

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
func jsonDateCalling(){
//Json Serilizarions
let jsonUrl = URL(string: "http://assetlinkasia.no-ip.biz:8001/hf_tracker/api/history.php?accesskey=12345&Vehilce=1618&FromDate=2018-05-10 13:11&ToDate=2018-05-14 12:11")
if let url = jsonUrl{
let data = NSData(contentsOf: url)
if let data = data{
do{
let jsonObject = try JSONSerialization.jsonObject(with: data as Date, options: .allowFragments)
if let object = jsonObject as? [NSString: AnyObject]{
if let allDevices = object["data"] as? [[NSString: AnyObject]]{
print("Successfull")
self.tableArray = allDevices
self.searchTextTableview.reloadData()
}
}
}catch{
print("Error Eccurred")
}
}
}
}
This is a work for json but i am facing "Cannot convert value of type 'NSData' to type 'Date' in coercion" how can i solve. and i am thinking this error for date parametter

1- Replace this
let jsonObject = try JSONSerialization.jsonObject(with: data as Date, options: .allowFragments)
with
let jsonObject = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
it's a Data object not Date
2- no need for fragments it can be
let jsonObject = try JSONSerialization.jsonObject(with: data as Data, options: [])
if let object = jsonObject as? [NSString: Any]
3- this line
let data = NSData(contentsOf: url)
blocks main thread consider using URLSession or Alamofire

Related

How to check JSON can be converted to dictionary in Swift?

Tried this, but get error:
var d = (try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as [String: String]
guard let d2 = d else {
return
}
You can try
guard let dic = try? JSONSerialization.jsonObject(with: data) as? [String: String] else { return }
The right tool here is JSONDecoder, not JSONSerialization:
let d = try JSONDecoder().decode([String: String].self, data)
.mutableContainers doesn't make sense when converting to a Swift Dictionary. That causes it to create NSMutableDictionary objects, which will just be converted to [String: String] exactly the same as without .mutableContainers (but possibly with an extra copy step).

Parsing value with try? and guard returning different values [duplicate]

This question already has answers here:
Optional binding with try? and as? still produces an optional type
(2 answers)
Closed 5 years ago.
Language Used: Swift 3
Xcode Version: 8.3.2 (8E2002)
I have an extension on Data which parses the data into a JSONObject of type Any
extension Data {
func toJsonObject() -> Any? {
do {
return try JSONSerialization.jsonObject(with: self, options: [])
} catch {
print(error)
}
return nil
}
}
Now the weird thing is when I use guard the result object seems to be different when using toJsonObject() and try?
For example
guard let dictionary = data.toJsonObject() as? [String: Any] else {
return
}
dictionary is now of type [String: Any]
Whereas when I use this:
guard let dictionary = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
return
}
dictionary is now of type [String: Any]?
Isn't the result of the second code block supposed to be [String: Any] instead of the optional [String: Any]?
Is this a mistake on Swift or am I doing something wrong?
This is a feature of Swift, I'd say. The use of try? means that this becomes a double optional, it's trying to decode straight to that casting of as? [String: Any]. Plug this in and check the type on this to see the double optional in action:
// Becomes a type of `[String : Any]??`
let dictionary = try? JSONSerialization.jsonObject(with: Data(), options: []) as? [String: Any]
I think the answer you want is to just add some parentheses to clarify your intent:
guard let dictionary = (try? JSONSerialization.jsonObject(with: Data(), options: [])) as? [String: Any] else {
return
}

Type 'Any' has no subscript memebers [duplicate]

This question already has answers here:
Correctly Parsing JSON in Swift 3
(10 answers)
Closed 6 years ago.
When i converted to swift 3 , its saying type any has no subscript memebers.
let dataDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
let accessToken = dataDictionary["access_token"] as! AnyObject?
Ihave tried many possiblities but didn't worked.
The return type of JSONSerialization.jsonObject(with:options:) is Any which doesn't allow subscripting. You have to use explicit type conversion to subscript. If you're trying to cast the data to [String: Any] you could do the following:
if let dataDictionary = dataDictionary as? [String: Any] {
// dataDictionary["access_token"] as AnyObject
}
JSONSerialization.jsonObject throws an error so let catch it in a do catch block
do {
let dataDictionary = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]
let accessToken = dataDictionary["access_token"] as! AnyObject
} catch let error as NSError {
print(error)
}

Getting nil value when read JSON data in Swift

if let postString = NSString(data:data!, encoding: NSUTF8StringEncoding) as? String {
guard let jsonData = postString.dataUsingEncoding(NSASCIIStringEncoding) else {
fatalError()
}
guard let jsonObjects = try? NSJSONSerialization.JSONObjectWithData(jsonData,options: [])
,let JSONArray = jsonObjects as? [[String: AnyObject]]
else {
fatalError()
}
print(JSONArray)
}
In postString constant, I am getting "[{\"Name\":\"ABC\",\"Age\":35},{\"Name\":\"CDE\",\"Age\":36‌​}]"
and when I run this code then fatalError() code call.
A couple of other people have explained what you did wrong in this case (Tried to cast the output of deserialization to a dictionary when it actually contains an array.)
Stepping back from the details, when something fails, you need to break your code into smaller pieces and then trace through it to see what's failing.
The "as?" cast says "Try to cast this object to another type. Wrap the results in an Optional." If the cast fails, the result is nil. If it succeeds, the optional contains the new type.
If you rewrote your code as:
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.AllowFragments)
guard let jsonDict = jsonObject as [String: Any] else {
print("Cast failed")
return
}
Then the print statement would fire and you'd know that the cast was the problem.
EDIT:
I just noticed that your JSON data contains an array of dictionaries of type [String: Int]. In Swift Ints are not an Object type, so you need to cast your results to [[String:Any]], not [[String:AnyObject]]. I've fixed my code above.
I Wrote the following code in a playground and it works:
let jsonString = "[{\"Name\":\"ABC\",\"Age\":35},{\"surveyName\":\"CDE\",\"Age\":36}]"
guard let jsonData = jsonString.data(using: .ascii) else {
fatalError()
}
guard let jsonObjects = try? JSONSerialization.jsonObject(with: jsonData, options: []),
let JSONArray = jsonObjects as? [[String: Any]]
else {
fatalError()
}
print(String(describing: jsonObjects))
It gives the output:
(
{
Age = 35;
Name = ABC;
},
{
Age = 36;
surveyName = CDE;
}
)
Which is what I would expect.
EDIT #2:
Actually, on further investigation I'm stumped as to why your code isn't working. I just tested it, and the as [[String: AnyObject]] works. It turns out that in Swift 3 if you cast an Int to AnyObject and you've included Foundation (or UIKit) then it gets silently converted to an NSNumber, which IS an Object type.
You're going to need to show your actual JSON data and the code that converts it to an object if you need help debugging it.
EDIT #3:
Below is code I wrote and tested in Swift 2.3:
func parseJSONTest() {
let jsonString = "[{\"Name\":\"ABC\",\"Age\":35},{\"surveyName\":\"CDE\",\"Age\":36}]"
guard let jsonData = jsonString.dataUsingEncoding(NSASCIIStringEncoding) else {
fatalError()
}
//I'm not sure why you take JSON data, convert it to a string, and convert
//It back to NSData, but to prove a point, this is your code being fed
//well-formed JSON data in an NSData object:
if let postString = NSString(data:jsonData,
encoding: NSASCIIStringEncoding) as? String {
guard let jsonData = postString.dataUsingEncoding(NSASCIIStringEncoding) else {
fatalError()
}
guard let jsonObjects = try? NSJSONSerialization.JSONObjectWithData(jsonData,options: []),
let JSONArray = jsonObjects as? [[String: AnyObject]]
else {
fatalError()
}
print(JSONArray)
}
}
In order to provide a complete test I first take a string containing JSON data and convert it to NSData. I then convert that NSData back to JSON objects and cast them to the desired type, and it works. The code above displays:
[["Name": ABC, "Age": 35], ["surveyName": CDE, "Age": 36]]
Which matches the structure you have (an array of dictionaries).
The above is technically not an json object it is a json array.
Try casting as [AnyObject] instead of [String: AnyObject]
Then use the array to access the item you need. Then cast that to
[String:AnyObject]
because they are json objects within a json array

Swift 3 error: Type 'Any' has no subscript members

So I know this question has been asked and answered numerous times before, but I just migrated my project to Swift 3 and Im getting a ton of these errors in my code that parses JSON and I couldn't quite find answers that made me understand how to resolve my specific issue.
guard let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] else {
return
}
guard let responseData = result["Data"] else { return }
guard let userData = responseData["UserProfile"] else { return }
var userProfileFieldsDict = [String: String]()
if let sessionToken = userData!["CurrentSessionToken"] as? NSString {
userProfileFieldsDict["sessionToken"] = String(sessionToken)
}
}
The if let sessionToken line throws the aforementioned error, but not quite sure how you're supposed to deal with this in Swift 3? Could someone explain and suggest a best practice fix?
Thanks a bunch!
If responseData["UserProfile"] is also a dictionary you'll probably want to cast it as such in you guard by saying guard let userData = responseData["UserProfile"] as? [String : AnyObject] else { return }. I suspect this will solve your problem.
As a small aside, you don't need to force unwrap userData in your if let, because you've already unwrapped it in the guard.