首页 > 解决方案 > 在 Swift 中将复杂的 JSON 保存到 Core Data

问题描述

我想将 Web 服务的 JSON 结果保存到核心数据,以下是 JSON 解析的代码。

if let jsonResult = try JSONSerialization.jsonObject(with: JSONData!, options: [.mutableContainers]) as? [String: AnyObject]

如果我打印 jsonResult,以下是输出

["Code": 00, "Desc": success, "iinData": <__NSArrayM 0x1c02531a0>
{
  name = “AAA”;
  iin = 123456;
  isOn = 0;
},
{
  name = "Allahabad Bank";
  iin = 608112;
  isOn = 0;
},
)

我可以将Code, Desc插入到 Entity1 中,但是如何将 innData 插入到 Entity2 中。

Entity1 结构 Entity2 结构

以下是将 JSON 结果插入核心数据的代码

func createEntity1From(dictionary: [String: AnyObject]) -> NSManagedObject? {
    let context = CoreDataStack.sharedInstance.persistentContainer.viewContext
    if let Entity1 = NSEntityDescription.insertNewObject(forEntityName: “ParamDownload”, into: context) as? ParamDownload {
        Entity1.Code= dictionary[“name”] as? String
        Entity1.desc = dictionary[“desc”] as? String
        return Entity1
    }
}

标签: iosjsonswiftcore-data

解决方案


将 JSON 直接解码为 Core Data 非常容易Decodable

  • 首先创建扩展CodingUserInfoKeyJSONDecoder能够传递托管对象上下文

    extension CodingUserInfoKey {
        static let context = CodingUserInfoKey(rawValue: "context")!
    }
    
    extension JSONDecoder {
        convenience init(context: NSManagedObjectContext) {
            self.init()
            self.userInfo[.context] = context
        }
    }
    
  • Decodable在两个类中添加一致性

    class Name: NSManagedObject, Decodable {
    
    class ParamDownload: NSManagedObject, Decodable {
    
  • 在类Name(不是扩展名)中添加

    private enum CodingKeys: String, CodingKey { case name, iin, isOn }
    
    required convenience init(from decoder: Decoder) throws {
        guard let context = decoder.userInfo[.context] as? NSManagedObjectContext else { fatalError("NSManagedObjectContext is missing") }
        let entity = NSEntityDescription.entity(forEntityName: "Name", in: context)!
        self.init(entity: entity, insertInto: context)
        let values = try decoder.container(keyedBy: CodingKeys.self)
        name = try values.decode(String.self, forKey: .name)
        iin = try values.decode(String.self.self, forKey: .iin)
        isOn = try values.decode(Bool.self.self, forKey: .isOn)
    }
    
  • 在类ParamDownload(不是扩展名)中添加

    private enum CodingKeys: String, CodingKey { case code = "Code", desc = "Desc", names = "iinData" }
    
    required convenience init(from decoder: Decoder) throws {
        guard let context = decoder.userInfo[.context] as? NSManagedObjectContext else { fatalError("NSManagedObjectContext is missing") }
        let entity = NSEntityDescription.entity(forEntityName: "ParamDownload", in: context)!
        self.init(entity: entity, insertInto: context)
        let values = try decoder.container(keyedBy: CodingKeys.self)
        code = try values.decode(String.self, forKey: .code)
        desc = try values.decode(String.self, forKey: .desc)
        names = try values.decode(Set<Name>.self, forKey: .names)
        names.forEach { $0.pd = self }
    }
    

要解码 JSON,请使用便利初始化程序创建解码器

let decoder = JSONDecoder(context: CoreDataStack.sharedInstance.persistentContainer.viewContext)

方法处理init关系。

我建议尽可能多地声明 Core Data 属性是非可选的。
如果一个属性必须是可选decode的,用decodeIfPresent.


推荐阅读