Swift 3中将CoreData对象转换为JSON [英] CoreData object to JSON in Swift 3

查看:307
本文介绍了Swift 3中将CoreData对象转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将CoreData对象转换为JSON,以便可以将其发送到Web服务器.

I'm struggling to get my CoreData objects into JSON so that I can use it to send to a web server.

这是我目前从CoreData获取对象的方式:

This is how I currently fetch my objects from CoreData:

func fetchRecord() -> [Record] {

    do {
        records = try context.fetch(Record.fetchRequest())

    } catch {
        print("Error fetching data from CoreData")
    }
    return records
}

我能够将其显示在我的桌子上,以这种方式查看:

I am able to display this on to my tableView this way:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "recordCell", for: indexPath) as! RecordCell

    cell.nameLbl.text = records[indexPath.row].name
    cell.quantityLbl.text = "Quantity: \(String(records[indexPath.row].quantity))"
    cell.dateLbl.text = dateString(date: records[indexPath.row].date)

    return cell
}

我试图像这样循环进入我的请求:

I have attempted to loop inside my request like this:

for rec in records {
    print(rec)
}

说明了这一点:

我已经阅读了很多有关实现此目标的方法,但是似乎没有一个对我真正有益.那里的大多数示例都展示了如何将JSON转换为CoreData,而不是其他方式.有人知道有什么好的教程或文档可以帮助我实现这一目标吗?

I have read a lot about ways to achieve this but none of them seem to really be of beneficial to me. Most of the examples out there shows how to get JSON to CoreData and not the other way. Does anyone know any good tutorials or documentation that can help me achieve this?

推荐答案

在Swift 4中,您可以利用Encodable协议并将功能直接添加到您的Core Data对象中.

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

假设您的NSManagedObject子类扩展名看起来像

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

   ...

采用Encodable

extension Record : Encodable {

并添加

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)
}

然后,您可以轻松地将记录编码为JSON

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")
}

这篇关于Swift 3中将CoreData对象转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆