Reputation: 155
as a coding exercise, I wrote a small program to take MySql data frm the web to the iPhone. On the server side. I wrote the php script to get the script to return the json data.
On xcode I have
[code]
.
.
.
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
.
.
.
[/code]
In xcode console, I have this:
[code]
(
{
Address = "1 Infinite Loop Cupertino, CA";
Latitude = "37.331741";
Longitude = "-122";
Name = Apple;
}
)
[/code]
I have a function
[code]
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
[/code]
When I pass the jsonString to convertToDictionary(text:)
[code]
let dict = convertToDictionary(text: jsonString as! String)
[/code]
In the console I get an error "Could not cast value of type '__NSSingleObjectArrayI' (0x10369bdb0) to 'NSString' (0x1004eac60)."
but if I hard code the json string then pass it to the convertToDictionary(text:)
[code]
let hardCodedStr = "{\"Address\":\"1 Infinite Loop Cupertino, CA\",\"Latitude\":\"37.331741\",\"Longitude\":\"-122\",\"Name\":\"Apple\"}"
let dict = convertToDictionary(text: hardCodedStr)
print(dict!)
[/code]
It works just fine. Why is that? Thanks
Upvotes: 5
Views: 12861
Reputation: 273540
If you look closely at what jsonObject(with:options:)
returns, you will see that it is a [String: Any]
or a [Any]
, depending on your JSON.
Therefore, jsonString
here actually stores a [String: Any]
, even thought the compiler thinks it is of type Any
:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: [])
print(jsonString!)
If you try to pass this to convertToDictionary
, which accepts a String
, it of course will not work, because a dictionary and String
are not compatible types.
How to solve this problem?
The problem is already solved! You don't need convertToDictionary
at all. jsonString
itself is the dictionary you wanted.
This is what you need to do:
let jsonString = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
^^^^^^^^^^^^^^^^^
Add this part
After that you can call dictionary methods on jsonString
. I also suggest you to rename jsonString
to something else.
Upvotes: 9