CoreData object to JSON in Swift 3

后端 未结 4 557
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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.

提交回复
热议问题