如何使用Swift将JSON可解码值存储到Coredata中 [英] How to store JSON decodable values into Coredata using Swift

查看:131
本文介绍了如何使用Swift将JSON可解码值存储到Coredata中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 JSON 数据加载到 CoreData 中。在这里,我使用JSON 结构进行可解码,之后,我尝试将可解码的数据提取到CoreData中。我不知道如何将可解码代码与 iterate 数据一起使用并提取到coredata中。下面的代码我尝试过,但是没有得到正确的结果。请帮我解决这个问题。

I am trying to load JSON Data into CoreData. Here, I used JSON structure for decodable and after that I am trying to fetch the decodable Data into CoreData. I don’t know how to use decodable with iterate the data and fetching into coredata. Below code I tried, but not getting proper result. Please help me to resolve this.

我的JSON

{
    "status": true,
    "data": [
        {
            "id": "20",
            "name": "ar1"
        },
        {
            "id": "21",
            "name": "ar2"
        },
        {
            "id": "22",
            "name": "ar3"
        }
    ]
}

我的JSON结构

struct userList: Codable {
    let status: Bool
    let data: [userData]
}

struct userData: Codable {
    let id, name: String
}

我的Coredata实体

var users = [User]() // User is my entity name

JSON可编码并尝试加载到CoreData

do {
       let result = try JSONDecoder().decode(userList.self, from:data) // here I am dong mistakes.
       let status = result.status
       if status == true {
           let newPerson = User(context: self.context)
           newPerson.id = "" // Cant able to get values
           newPerson.name = ""
           self.users.append(newPerson)

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                self.tableView.reloadData()
             }
            } else {
               print(error)
             }

    } catch {
         print(error)
}


推荐答案

要将JSON直接解码为Core Data类,您必须采用Decodable

To be able to decode JSON directly into Core Data classes you have to adopt Decodable


  • 实施两个扩展才能传递托管对象上下文通过 JSONDecoder

extension CodingUserInfoKey {
    static let context = CodingUserInfoKey(rawValue: "context")!
}

extension JSONDecoder {
    convenience init(context: NSManagedObjectContext) {
        self.init()
        self.userInfo[.context] = context
    }
}


  • User中采用可解码的并添加 CodingKeys 和必需的 init(from 方法

  • In User adopt Decodable and add CodingKeys and the required init(from method

    public class User: NSManagedObject, Decodable {
    
        private enum CodingKeys: String, CodingKey { case name, id }
    
        public required convenience init(from decoder: Decoder) throws {
            guard let context = decoder.userInfo[.context] as? NSManagedObjectContext else { fatalError("Error: with managed object context!") }
            let entity = NSEntityDescription.entity(forEntityName: "User", in: context)!
            self.init(entity: entity, insertInto: context)
            let values = try decoder.container(keyedBy: CodingKeys.self)
            name = try values.decode(String.self, forKey: .name)
            id = try values.decode(String.self, forKey: .id)
        }
    ...
    


  • 现在您只需要一个伞形结构作为根对象。再次请始终以大写字母开头来命名结构

  • Now you need only one umbrella struct for the root object. Once again please name structs always with starting uppercase letter

    struct Root: Decodable {
        let status: Bool
        let data: [User]
    }
    


  • 要解码JSON,请使用自定义初始化程序, User 实例会自动插入数据库中

  • To decode the JSON use the custom initializer, the User instances are inserted automatically into the database

    do {
        let decoder = JSONDecoder(context: context) // context is the NSManagedObjectContext instance 
        let result = try decoder.decode(Root.self, from: data)
        if result.status {
           print("success")
           try context.save()
        }  
    catch { print(error)
    


  • 这篇关于如何使用Swift将JSON可解码值存储到Coredata中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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