在Swift中将Dictionary转换为JSON

Ork*_*ade 169 serialization json swift

我创建了下一个词典:

var postJSON = [ids[0]:answersArray[0], ids[1]:answersArray[1], ids[2]:answersArray[2]] as Dictionary
Run Code Online (Sandbox Code Playgroud)

我得到:

[2: B, 1: A, 3: C]
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能将它转换为JSON?

aya*_*aio 220

Swift 3.0

NSJSONSerialization根据Swift API设计指南,使用Swift 3,其名称及其方法已发生变化.

let dic = ["2": "B", "1": "A", "3": "C"]

do {
    let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
    // here "decoded" is of type `Any`, decoded from JSON data

    // you can now cast it with the right type        
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch {
    print(error.localizedDescription)
}
Run Code Online (Sandbox Code Playgroud)

Swift 2.x

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted)
    // here "jsonData" is the dictionary encoded in JSON data

    let decoded = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // here "decoded" is of type `AnyObject`, decoded from JSON data

    // you can now cast it with the right type 
    if let dictFromJSON = decoded as? [String:String] {
        // use dictFromJSON
    }
} catch let error as NSError {
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特1

var error: NSError?
if let jsonData = NSJSONSerialization.dataWithJSONObject(dic, options: NSJSONWritingOptions.PrettyPrinted, error: &error) {
    if error != nil {
        println(error)
    } else {
        // here "jsonData" is the dictionary encoded in JSON data
    }
}

if let decoded = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as? [String:String] {
    if error != nil {
        println(error)
    } else {
        // here "decoded" is the dictionary decoded from JSON data
    }
}
Run Code Online (Sandbox Code Playgroud)

  • JSON 大括号,如 `{"result":[{"body":"Question 3"}] }` (2认同)
  • @OrkhanAlizade上面对`dataWithJSONObject` _would_的调用产生了"花括号"(即大括号)作为生成的`NSData`对象的一部分. (2认同)
  • 哇欣赏**Swift 3**的第一次更新 (2认同)

Dun*_*n C 146

你做出了错误的假设.只是因为调试器/ Playground在方括号中显示您的字典(这是Cocoa显示字典的方式)并不意味着JSON输出的格式化方式.

以下是将字符串字典转换为JSON的示例代码:

Swift 3版本:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
if let theJSONData = try? JSONSerialization.data(
    withJSONObject: dictionary,
    options: []) {
    let theJSONText = String(data: theJSONData,
                               encoding: .ascii)
    print("JSON string = \(theJSONText!)")
}
Run Code Online (Sandbox Code Playgroud)

要以"漂亮打印"格式显示上述内容,您需要将选项行更改为:

    options: [.prettyPrinted]
Run Code Online (Sandbox Code Playgroud)

或者在Swift 2语法中:

import Foundation

let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
let theJSONData = NSJSONSerialization.dataWithJSONObject(
  dictionary ,
  options: NSJSONWritingOptions(0),
  error: nil)
let theJSONText = NSString(data: theJSONData!,
  encoding: NSASCIIStringEncoding)
println("JSON string = \(theJSONText!)")
Run Code Online (Sandbox Code Playgroud)

输出是

"JSON string = {"anotherKey":"anotherValue","aKey":"aValue"}"
Run Code Online (Sandbox Code Playgroud)

或者是漂亮的格式:

{
  "anotherKey" : "anotherValue",
  "aKey" : "aValue"
}
Run Code Online (Sandbox Code Playgroud)

正如您所期望的那样,字典在JSON输出中用大括号括起来.

编辑:

在Swift 3/4语法中,上面的代码如下所示:

  let dictionary = ["aKey": "aValue", "anotherKey": "anotherValue"]
    if let theJSONData = try?  JSONSerialization.data(
      withJSONObject: dictionary,
      options: .prettyPrinted
      ),
      let theJSONText = String(data: theJSONData,
                               encoding: String.Encoding.ascii) {
          print("JSON string = \n\(theJSONText)")
    }
  }
Run Code Online (Sandbox Code Playgroud)


use*_*143 26

我对你的问题的回答如下

let dict = ["0": "ArrayObjectOne", "1": "ArrayObjecttwo", "2": "ArrayObjectThree"]

var error : NSError?

let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted)

let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String

print(jsonString)
Run Code Online (Sandbox Code Playgroud)

答案是

{
  "0" : "ArrayObjectOne",
  "1" : "ArrayObjecttwo",
  "2" : "ArrayObjectThree"
}
Run Code Online (Sandbox Code Playgroud)


Rya*_*n H 25

斯威夫特4:

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,键和值必须实现Codable.字符串,Ints和双打(以及更多)已经存在Codable.请参阅编码和解码自定义类型.

  • 仅供将来参考,如果您的字典类型为 [String, Any],则此解决方案将不起作用 (7认同)

And*_*eev 21

有时需要打印出服务器的响应以进行调试.这是我使用的一个功能:

extension Dictionary {

    var json: String {
        let invalidJson = "Not a valid JSON"
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
            return String(bytes: jsonData, encoding: String.Encoding.utf8) ?? invalidJson
        } catch {
            return invalidJson
        }
    }

    func printJson() {
        print(json)
    }

}
Run Code Online (Sandbox Code Playgroud)

使用示例:

(lldb) po dictionary.printJson()
{
  "InviteId" : 2,
  "EventId" : 13591,
  "Messages" : [
    {
      "SenderUserId" : 9514,
      "MessageText" : "test",
      "RecipientUserId" : 9470
    },
    {
      "SenderUserId" : 9514,
      "MessageText" : "test",
      "RecipientUserId" : 9470
    }
  ],
  "TargetUserId" : 9470,
  "InvitedUsers" : [
    9470
  ],
  "InvitingUserId" : 9514,
  "WillGo" : true,
  "DateCreated" : "2016-08-24 14:01:08 +00:00"
}
Run Code Online (Sandbox Code Playgroud)


the*_*nde 17

Swift 4 Dictionary扩展.

extension Dictionary {
    var jsonStringRepresentation: String? {
        guard let theJSONData = try? JSONSerialization.data(withJSONObject: self,
                                                            options: [.prettyPrinted]) else {
            return nil
        }

        return String(data: theJSONData, encoding: .ascii)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在公共扩展中使用“encoding: .ascii”不是一个好主意。`.utf8` 会更安全! (2认同)

Ale*_*kov 9

斯威夫特 5:

extension Dictionary {
    
    /// Convert Dictionary to JSON string
    /// - Throws: exception if dictionary cannot be converted to JSON data or when data cannot be converted to UTF8 string
    /// - Returns: JSON string
    func toJson() throws -> String {
        let data = try JSONSerialization.data(withJSONObject: self)
        if let string = String(data: data, encoding: .utf8) {
            return string
        }
        throw NSError(domain: "Dictionary", code: 1, userInfo: ["message": "Data cannot be converted to .utf8 string"])
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 8

斯威夫特3:

let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
let jsonString = String(data: jsonData!, encoding: .utf8)!
print(jsonString)
Run Code Online (Sandbox Code Playgroud)


Rei*_*ill 6

在斯威夫特 5.4 中

extension Dictionary {
    var jsonData: Data? {
        return try? JSONSerialization.data(withJSONObject: self, options: [.prettyPrinted])
    }
    
    func toJSONString() -> String? {
        if let jsonData = jsonData {
            let jsonString = String(data: jsonData, encoding: .utf8)
            return jsonString
        }
        
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

将其作为变量的想法是因为这样您就可以像这样重用它:

extension Dictionary {
    func decode<T:Codable>() throws -> T {
        return try JSONDecoder().decode(T.self, from: jsonData ?? Data())
    }
}
Run Code Online (Sandbox Code Playgroud)


Dhe*_*j D 5

您的问题的答案如下:

斯威夫特2.1

     do {
          if let postData : NSData = try NSJSONSerialization.dataWithJSONObject(dictDataToBeConverted, options: NSJSONWritingOptions.PrettyPrinted){

          let json = NSString(data: postData, encoding: NSUTF8StringEncoding)! as String
          print(json)}

        }
        catch {
           print(error)
        }
Run Code Online (Sandbox Code Playgroud)