user2873720 user2873720 - 22 days ago 14
JSON Question

Convert an array of objects to JsonArray in Swift3

I have my DataModel as this and it has a function name toJSON which converts this object to string representation of JSON

ContactEntry: NSObject {
var name: String!
var phone: String?
var email: String?

func toJson() -> String {
var dict : [String: AnyObject] = [:]
dict["name"] = (self.name ?? "") as AnyObject
dict["phone"] = (self.phone ?? "") as AnyObject
dict["email"] = (self.email ?? "") as AnyObject


guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []) else{
return "{}"
}

guard let jsonString = String(data: data, encoding: String.Encoding.utf8) else {
return "{}"
}
return jsonString
}
}


It works very fine until now as I am getting correct JSON representation for this object.

Now I have to convert an array of ContactEntry to JsonArray.

I am doing this way but I am getting very weird symbols in the result string.
Let's say

var contacts = [ContactEntry]()
var contactsStr = [String]()
...
for contact in contacts{
contactsStr.append(contact.toJson())
}

do{
let data = try? JSONSerialization.data(withJSONObject: contactsStr, options: [])

let jsonString = try? String(data: data!, encoding: String.Encoding.utf8)

print(jsonString)
}


I am getting the output like this

[\n \"{\\\"phone\\\":\\\"+XXXX\\\",\\\"name\\\":\\\"YYYY\\\",\\\"email\\\":\\\"\\\"},\",\n \".........\n]


Please help me to do it in a better and clean way

Thanks for your help

Answer

I think you are double serializing your output. That's why I asked for the contact string.

Try:

func toJson() -> [String: AnyObject] {
    var dict : [String: AnyObject] = [:]
    dict["name"] = (self.name ??  "") as AnyObject
    dict["phone"] = (self.phone ?? "") as AnyObject
    dict["email"] = (self.email ?? "") as AnyObject
    return dict
}

With:

var contactsStr = [[String: AnyObject]]()

And print out the serialization. It should just be singly escaping quotes such as \"name\". Not \\"name\\"

Comments