如何在 swift 中解析 "jSON" 数据后在字典中追加值?

How to append value in dictionary after parsed "jSON" Data in swift?

这是我的代码。

func connectionDidFinishLoading(connection: NSURLConnection){

    var err: NSError
    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

    if jsonResult.count>0 && jsonResult["results"]!.count>0 {
        var result: NSArray = jsonResult["results"] as! NSArray
        println("\(result)")
        var dict = NSDictionary()
        var myDict = NSDictionary()

        for dict in result {
            let googleGeo = dict["geometry"] as! NSDictionary
            let googleLoc = googleGeo["location"] as! NSDictionary
            let latitude = googleLoc["lat"] as! Float
            let longitude = googleLoc["lng"] as! Float
            let googleicon = dict.valueForKey("icon") as? NSString
            let googlename = dict["name"] as? NSString
            let googlevicinity = dict["vicinity"] as? NSString

            myDict.setValue(latitude, forKey: "lat"    
        }
    }
}

从 Google 个地点 API 解析后,我收到了经度、纬度、名称、附近区域、图标。现在我想将这些值附加到 myDctionary 以便我可以将值传递给数组和下一个视图控制器。

请有人告诉我该怎么做?

朋友,你应该试试这个。

让字典确切地知道您希望它保留哪种类型的 key/value 对。您希望使用 "String" 作为键,并且由于您的值具有不同的数据类型,因此您希望使用 "AnyObject" 作为值。

UPDATE 对于 Swift 2,您将使用 String:AnyObject,但对于 Swift3,您将使用 String:Any。我更新了代码以显示 Swift 3 版本。

//this says your dictionary will accept key value pairs as String/Any
var myDict = [String:Any]()

你使用 Any 是因为你有很多不同的数据类型

//Your values have are being cast as NSDictionary, Float, and NSStrings. All different datatypes
let googleGeo = dict["geometry"] as? NSDictionary
let googleLoc = googleGeo["location"] as? NSDictionary
let latitude = googleLoc["lat"] as? Float
let longitude = googleLoc["lng"] as? Float
let googleicon = dict.valueForKey("icon") as? NSString
let googlename = dict["name"] as? NSString
let googlevicinity = dict["vicinity"] as? NSString

现在你使用方法 .updateValue(value: Value, forKey: Hashable) 来设置你的键和值

//update the dictionary with the new values with value-type Any and key-type String
myDict.updateValue(googleGeo, forKey: "geometry")
myDict.updateValue(googleLoc, forKey: "location")
myDict.updateValue(latitude, forKey: "lat")
myDict.updateValue(longitude, forKey: "lng")
myDict.updateValue(googleicon, forKey: "icon")
myDict.updateValue(googlename, forKey: "name")
myDict.updateValue(googlevicinity, forKey: "vicinity")

myDict 现在应该拥有所有这些 key/value 对,你可以通过使用键提取值来对它们做你想做的事。顺便说一句,我只使用了那些键名,因为对于您的 post 来说,这似乎是您使用的约定。您可以随意命名键。但是无论您如何命名它们,它们都必须与您用来提取值的名称相同。

希望对您有所帮助!