Convert a JSON string to Dictionary in Swift 3

牧云@^-^@ 提交于 2019-12-23 12:28:18

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/44355525/convert-a-json-string-to-dictionary-in-swift-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!