核心数据-NSManagedObject(具有关系)到JSON

时间:2018-07-13 07:44:18

标签: json swift core-data

我是Core Data的新手,我想将NSManagedObject(从本地数据库获取)转换为JSON字符串。如上所示,这是一个具有关系的简单对象:

Entities

那是我用来获取的代码:

func loadData() {
    //1
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }

    let managedContext = appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Bill")

    //3
    do {
        let fetchedData = try managedContext.fetch(fetchRequest) as! [Bill]
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
}

如何将fetchedData转换为JSON字符串?我想使用Codable,但我不知道它是否受支持。

1 个答案:

答案 0 :(得分:0)

为每个类创建一个扩展,并使其实现Encodable。像这样的地段

extension Lot: Encodable {
  enum CodingKeys: String, CodingKey {
    case id
    case quantity
    case expiration
    case quantity_packages
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try container.encode(quantity, forKey: . quantity)
    try container.encode(expiration, forKey: . expiration)
    try container.encode(quantity_packages, forKey: . quantity_packages)
}

对于Bill,请注意,我将lotsNSSet转换为Array

extension Bill: Encodable {
  enum CodingKeys: String, CodingKey {
    case id
    case name
    case lots
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try container.encode(name, forKey: .name)
    if let array = lots?.allObjects as? [Lot] {
        try container.encode(array, forKey: .lots)
    } // else Not sure what to do here, maybe use an empty array?
  }
}

我无法正确测试它,但希望对您有所帮助。