gpt4 book ai didi

json - swift 2 : Natively serialize JSON to Core Data Model Objects

转载 作者:行者123 更新时间:2023-11-28 08:52:07 26 4
gpt4 key购买 nike

我想将 JSON 序列化为核心数据模型对象,来回进行。我正在从 RestKIT 切换到 Alamofire 和 Swifty JSON。我知道有些库可以提供此功能,但我想知道如何在本地执行此操作?

下面是核心数据设置:

enter image description here

事件+CoreDataProperties.swift

import Foundation
import CoreData

extension Event {

@NSManaged var id: NSNumber?
@NSManaged var name: String?
@NSManaged var realRame: String?
@NSManaged var notes: NSSet?

}

事件.swift

import Foundation
import CoreData

class Event: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}

Notes+CoreDataProperties.swift

import Foundation
import CoreData

extension Notes {

@NSManaged var id: NSNumber?
@NSManaged var name: String?
@NSManaged var event: Event?

}

笔记.swift

导入基金会导入核心数据

类笔记:NSManagedObject {//在此处插入代码以向托管对象子类添加功能

下面是收到的JSON:

{
"id": "5555",
"name": "Superman",
"realName": "Clark Kent",
"notes": [
{
"id": "2",
"name": "Order Flowers"
},
{
"id": "3",
"name": "Pick up Laundry"
}
{
"id": "4",
"name": "Get Chinese Food"
},
]
}

获取JSON的代码:

Alamofire.request(fetchData(param)).responseJSON { (response) in

switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}

问题:我不确定从这里到哪里去。 NSJSONSerialization 似乎需要 NSData 格式的数据。

代码示例将不胜感激。

最佳答案

添加新类 DBManager:

class DBManager: NSObject {
var managedObjectContext:NSManagedObjectContext!
var managedObjectModel:NSManagedObjectModel!

func insertData(jsonObj: AnyObject) {
let entity = NSEntityDescription.entity(forEntityName: "Event",
in:managedObjectContext)
let obj = NSManagedObject(entity: entity!,
insertInto: managedObjectContext)

obj.setValue(String((jsonObj.value(forKey: "id"))!) , forKey: "id")

....

继续设置其他属性的值。

在 AppDelegate 中声明这个变量:

var objDb = DBManager()

添加这个

switch response.result {
case .Success:
if let value = response.result.value {
let json = JSON(value)

let anyObjects: AnyObject = json as! AnyObject
let appDelegate = UIApplication.shared().delegate as! AppDelegate
appDelegate.objDb.insertData(jsonObj: anyObjects)
}
case .Failure(let error):
print("Request failed with error: \(error)")
}

关于json - swift 2 : Natively serialize JSON to Core Data Model Objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com