【问题标题】:Storing JSON Dictionary Values into Variables将 JSON 字典值存储到变量中
【发布时间】:2016-06-11 11:51:18
【问题描述】:

使用 PHP 文件,我以以下格式回显来自 MySQL 数据库的数据:[{"longitude":"-122.031","latitude":"37.3323”}]

在我的 Swift 文件中,我使用 NSJSONSerialization.JSONObjectWithData() 创建一个如下所示的 JSON 字典

(

    {

        latitude = "37.3323";

        longitude = "-122.031";

    }

)

如果我想将单个字典值存储在变量中,我相信下面的 Swift 代码 sn-p 会起作用

class Location: NSObject {
    var latitude: String?
    var longitude: String?
}

var locations = [Location]()

if let locationDictionary = jsonDictionary["coordinates"] as? [String: AnyObject] {
        let location = Location()

        location.setValuesForKeysWithDictionary(locationDictionary)

        print(location.latitude, location.longitude)
}

我遇到的唯一问题是我的 JSON 字典看起来像

(

    coordinates =  {

        latitude = "37.3323";

        longitude = "-122.031";

    }

)

但我不知道要采取什么步骤来实现这一目标。

【问题讨论】:

    标签: php json swift dictionary


    【解决方案1】:

    你必须像这样制作你的 JSON:

    [{"坐标":{"经度":"-122.031","纬度":"37.3323"}}]

    这是一个字典数组,其中每个字典包含另一个字典。

    这里是你的代码适应新格式:

    if let json = try? NSJSONSerialization.JSONObjectWithData(data, options: []), // your source may differ, I'm just using this line for my example
        content = json as? [[String:AnyObject]] { // the array of dictionaries
        for item in content {
            if let locationDictionary = item["coordinates"] as? [String: AnyObject] { // the dictionary inside the dictionary
                let location = Location()
                location.setValuesForKeysWithDictionary(locationDictionary)
                print(location.latitude, location.longitude)
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      相关资源
      最近更新 更多