2015-11-28 68 views
1

我想將JSON序列化爲核心數據模型對象,並來回訪問。我正在從RestKIT切換到Alamofire和Swifty JSON。我知道有些庫提供了這些,但我想知道如何在本地執行此操作?Swift 2:本地將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? 

} 

Event.swift

import Foundation 
import CoreData 

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

票據+ CoreDataProperties.swift

import Foundation 
import CoreData 

extension Notes { 

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

} 

Notes.swift

進口基金會 進口CoreData

類注: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格式的數據。

代碼示例將不勝感激。

+0

如果在JSON越來越響應,那麼你就可以直接使用鍵值對訪問值存放在的NSMutableDictionary和。爲什麼你需要使用NSJSONSerialization? –

+0

我正在使用SwiftyJSON從JSON轉換爲對象。我如何回去的話? – user1107173

回答

0

添加新類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)") 
     }