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
contactsStr?prettyPrinted, that causes most of the weird output