【问题标题】:Convert Swift 3 Array to JSON将 Swift 3 数组转换为 JSON
【发布时间】:2017-01-04 03:22:01
【问题描述】:

我有字典数组 [[String:Any]] 我想将其转换为 JSON 字符串。但我不知道如何开始。我尝试了 JSONSerialization.data(withJSONObject: array, options: .prettyPrinted) 并将数组传递给方法,但它显示错误。任何解决方案请在下方评论。谢谢。

【问题讨论】:

  • 你能附上你的代码吗?
  • 如果这是一个 Swift 问题,请添加相关标签。此外,您应该提供您的尝试显示的具体错误。

标签: arrays json


【解决方案1】:

试试下面的代码...

do {

    //Convert to Data
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryArray, options: JSONSerialization.WritingOptions.prettyPrinted)

    //Do this for print data only otherwise skip
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
       print(JSONString)
    }

    //In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [AnyObject].
    var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: AnyObject]


    } catch {
        print(error.description)
    }

【讨论】:

    猜你喜欢
    • 2018-12-08
    • 2017-04-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    相关资源
    最近更新 更多