Swift3 - JSON 字符串的字典

Swift3 - Dictionary to JSON String

我有以下class(在实际聊天中class是NSManagedObject,为了清楚起见我简化了它)

import Foundation
class Chat: Hashable {

    public var id: Int32?
    public var token: String?
    public var title: String?

    var hashValue: Int {
        return ObjectIdentifier(self).hashValue
    }

    static func ==(lhs: Chat, rhs: Chat) -> Bool {
        return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
    }
}

我在这里初始化对象并将其存储在集合中(实际上这个数据是使用核心数据获取的,类型总是Set。因此我尝试复制相同的类型)

let chat1 = Chat()
chat1.id = 1
chat1.token = "aU7nanPu"
chat1.title  = "Chat Title 1"

let chat2 = Chat()
chat2.id = 2
chat2.token = "948dfjh4"
chat2.title  = "Chat Title 2"

let chat3 = Chat()
chat3.id = 3
chat3.token = "1321sjadb"
chat3.title  = "Chat Title 3"

var chats = Set<Chat>()
chats.insert(chat1)
chats.insert(chat2)
chats.insert(chat3)

我现在想将数据转换成JSON发送到服务器进行处理。 (我将 Alamofire 与 SwiftyJSON 一起使用)因此我首先使用以下代码将其转换为字典。

var resultDict = [Int:Any]()
for (index, chat) in chats.enumerated() {
    var params = ["id" : chat.id!, "token": chat.token!, "title": chat.title!] as [String : Any]
    resultDict[index] = params
}

这给了我以下输出

[2: ["id": 3, "token": "1321sjadb", "title": "Chat Title 3"], 0: ["id": 1, "token": "aU7nanPu", "title": "Chat Title 1"], 1: ["id": 2, "token": "948dfjh4", "title": "Chat Title 2"]]

我现在想将此输出转换为 JSON。这是我试过的。

let jsonData = try! JSONSerialization.data(withJSONObject: resultDict, options: .prettyPrinted)

这给了我一个错误 Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary

我的问题是,如何将 resultDict 变量转换为有效的 JSON 字符串格式?

PS:如果有人想玩代码,这里是 fiddle:https://swift.sandbox.bluemix.net/#/repl/597833e605543472066ad11e

我相信 resultDict 需要它的键是字符串类型。

 let resultDict = [String:Any]()

只需将索引转换为字符串,然后再将其添加到字典中

 resultDict[String(index)] = params

您的 resultDict[Int:Any] 类型并且 JSONSerialization 需要键是 strings https://developer.apple.com/documentation/foundation/jsonserialization/1413636-data了解更多详情。

how do I convert resultDict variable into valid JSON string format

试试这个

var resultDict = [String:Any]()
for (index, chat) in chats.enumerated() {
    var params = ["id" : chat.id!, "token": chat.token!, "title": chat.title!] as [String : Any]
    resultDict["\(index)"] = params
}