JSONSerialization with Swift 3

后端 未结 2 479
温柔的废话
温柔的废话 2020-12-17 21:19

I am having a bear of a time understanding simple JSON serialization principles with Swift 3. Can I please get some help with decoding JSON from a website into an array so I

相关标签:
2条回答
  • 2020-12-17 21:42

    Thank you. The information from OOPer helped. But, what really helped was reformatting my json:

    { "teams": [ { "a": 1, "b": 2, "c": "red" }, { "a": 1, "b": 2, "c": "yellow" }, { "a": 1, "b": 2, "c": "green" } ] }
    
    0 讨论(0)
  • 2020-12-17 21:57

    In Swift 3, the return type of JSONSerialization.jsonObject(with:options:) has become Any.

    (You can check it in the Quick Help pane of your Xcode, with pointing on jsonResult.)

    And you cannot call any methods or subscripts for the variable typed as Any. You need explicit type conversion to work with Any.

        if let jsonResult = jsonResult as? [String: Any] {
            print(jsonResult["team1"])
        }
    

    And the default Element type of NSArray, the default Value type of NSDictionary have also become Any. (All these things are simply called as "id-as-Any", SE-0116.)

    So, if you want go deeper into you JSON structure, you may need some other explicit type conversion.

            if let team1 = jsonResult["team1"] as? [String: Any] {
                print(team1["a"])
                print(team1["b"])
                print(team1["c"])
            }
    
    0 讨论(0)
提交回复
热议问题