swift - Swift3 - Dictionary to JSON String -


i have following class (in actual chat class nsmanagedobject, simplified clarity)

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)     } } 

here initializing object , storing in set (in actual data fetched using core-data , type set. hence tried replicating same type)

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) 

i want convert data json send server processing. (i using alamofire swiftyjson) hence first converted dictionary using following code.

var resultdict = [int:any]() (index, chat) in chats.enumerated() {     var params = ["id" : chat.id!, "token": chat.token!, "title": chat.title!] [string : any]     resultdict[index] = params } 

this gave me following output

[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"]]

i want convert output json. here tried.

let jsondata = try! jsonserialization.data(withjsonobject: resultdict, options: .prettyprinted) 

this gives me error says terminating app due uncaught exception 'nsinvalidargumentexception', reason: 'invalid (non-string) key in json dictionary

my question is, how convert resultdict variable valid json string format?

ps: in-case if wants play code, here fiddle: https://swift.sandbox.bluemix.net/#/repl/597833e605543472066ad11e

i believe resultdict needs key of type string.

 let resultdict = [string:any]() 

just convert index string before adding dictionary

 resultdict[string(index)] = params 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -