【问题标题】:Convert NSARRAY to NSDictionary to be used as a result of JSon serialisation swift4 Xcode 9 [closed]将 NSARRAY 转换为 NSDictionary 以用作 JSON 序列化 swift4 Xcode 9 [关闭]
【发布时间】:2018-02-02 09:19:17
【问题描述】:

我想将NSArray 转换为NSDictionary,然后选择NSDictionary 中的键和值,以便以后能够使用键将NSDictionary 中的数据添加到对象中在里面。

我怎样才能以最聪明的方式做到这一点?

这是我目前所拥有的:

func makeCall(completion: result: NSDictionary or Dictionary){
    let json = try JSONSerialization.jsonObject(with: data!, options:  JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary
    let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? Array<Any>
}

这两个 JSON 文件看起来几乎相同。不同之处在于 var 类型,因此您将获得键和值,但采用数组样式。我们需要它以字典样式通过键获取值。

【问题讨论】:

  • 你能添加一个例子让你的问题更清楚吗?
  • 尽可能不要在 Swift 中使用 NS 类

标签: swift nsarray converter nsdictionary


【解决方案1】:

斯威夫特 4

在 Swift 中,您应该使用 Dictionary,并且仅在您明确需要该类型时才使用 NSDictionary。

    //your NSArray
    let myArray: NSArray = ["item1","item2","item3"]

    //initialize an emtpy dictionaty
    var myDictionary = [String:String]()

    //iterate through the array
    for item in myArray
    {
        //add array items to dictionary as key with any value you prefer
        myDictionary.updateValue("some value", forKey: item as! String)
    }

    //now you can use myDictionary as Dictionary
    print ("my dictionary: ")
    print (myDictionary)

    //if you prefer to use it as an NSDictionary
    let myNSDictionary = myDictionary as NSDictionary!
    print ("my NSDictionary: ")
    print (myNSDictionary)

【讨论】:

  • 我们从 Json 文件中获取数据并将其放入数组中。 Json 文件看起来像这种类型:名称子类型:名称 whenCreated:时间 keyForData:数据。我们如何将我们已经在数组中获得的键用于我们也在数组中获得的数据?
  • 在 Swift 中你应该使用数组你明确不需要需要NSArray?你不需要'在 Swift 中根本不需要 NSArrayNSDictionary 进行 JSON 反序列化,永远不会。
  • 您可以将从服务接收到的数据直接转换为 NSArray,而不是访问值 let data: Data = dataFromServer let myNSArray = try!JSONSerialization.jsonObject(with: data, options: . mutableLeaves) 作为? NSArray
猜你喜欢
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
相关资源
最近更新 更多