CoreData object to JSON in Swift 3

后端 未结 4 556
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-01 06:49

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:



        
相关标签:
4条回答
  • 2021-01-01 07:05

    If you want you can get the results in dictionary format from core data using below :

    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName:"Record")
    fetchRequest.resultType = .dictionaryResultType
    do {
        records = try context.fetch(fetchRequest)
    } catch {
        print("Error fetching data from CoreData")
    }
    
    0 讨论(0)
  • 2021-01-01 07:16

    In Swift 4 you can take advantage of the Encodable protocol and add the functionality directly to your Core Data object.

    Assuming your NSManagedObject subclass extension looks like

    extension Record {
    
        @NSManaged public var date: Date
        @NSManaged public var name: String
        @NSManaged public var quantity: Int32
        @NSManaged public var synched: Bool
        @NSManaged public var uuid: String
    
       ...
    

    Adopt Encodable

    extension Record : Encodable {
    

    and add

    private enum CodingKeys: String, CodingKey { case date, name, quantity, synched, uuid }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(date, forKey: .date)
        try container.encode(name, forKey: .name)
        try container.encode(quantity, forKey: .quantity)
        try container.encode(synched, forKey: .synched)
        try container.encode(uuid, forKey: .uuid)
    }
    

    Then you can easily encode the records to JSON

    do {
        records = try context.fetch(Record.fetchRequest())
        let jsonData = try JSONEncoder().encode(records)
    } catch {
        print("Error fetching data from CoreData")
    }
    
    0 讨论(0)
  • 2021-01-01 07:23

    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)
    
    0 讨论(0)
  • 2021-01-01 07:24

    You can convert your NSManageObject subclass object into dictionary by using following code

    let record = recArray[index]
            let keys = Array(record.entity.attributesByName.keys)
            let dict = record.dictionaryWithValues(forKeys: keys)
    

    After that you can use jsonserialization to convert that dictionary into json object

    do{
            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
            let reqJSONStr = String(data: jsonData, encoding: .utf8)
            print(reqJSONStr!)
        }catch{
    
        }
    

    Hope this will help.

    0 讨论(0)
提交回复
热议问题