I\'m struggling to get my CoreData objects into JSON so that I can use it to send to a web server.
This is how I currently fetch my objects from CoreData:
Here the code as an extension. Based on KavyaKavita's answer.
extension NSManagedObject {
func toJSON() -> String? {
let keys = Array(self.entity.attributesByName.keys)
let dict = self.dictionaryWithValues(forKeys: keys)
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let reqJSONStr = String(data: jsonData, encoding: .utf8)
return reqJSONStr
}
catch{}
return nil
}
}
Usage:
let jsonString = YourCoreDataObject.toJSON()
print(jsonString)