我有以下类(在实际的Chat类中是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中(实际上这个数据是使用core-data获取的,类型总是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)因此我首先使用以下代码将其转换为Dictionary。
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:[&#34; id&#34;:3,&#34;令牌&#34;:&#34; 1321sjadb&#34;,&#34;标题&#34;:&#34;聊天标题3&#34;],0: [&#34; id&#34;:1,&#34;令牌&#34;:&#34; aU7nanPu&#34;,&#34;标题&#34;:&#34;聊天标题1&#34;] ,1:[&#34; id&#34;:2, &#34; token&#34;:&#34; 948dfjh4&#34;,&#34; title&#34;:&#34; Chat Title 2&#34;]]
我现在想将此输出转换为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:如果有人想要使用代码,以防万一:https://swift.sandbox.bluemix.net/#/repl/597833e605543472066ad11e
答案 0 :(得分:1)
我相信resultDict需要它的键是String类型。
let resultDict = [String:Any]()
在将索引添加到词典之前,只需将索引转换为字符串
resultDict[String(index)] = params
答案 1 :(得分:1)
您的resultDict
类型为[Int:Any]
,而JSONSerialization需要密钥为strings
https://developer.apple.com/documentation/foundation/jsonserialization/1413636-data了解更多详情。
如何将resultDict变量转换为有效的JSON字符串格式
试试这个
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
}