简体   繁体   中英

How to store JSON response in Core Data?

I have a Core Data object.

I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to store JSON responses as Core Data objects.

I'm getting 5 records (dictionaries) from JSON response. I need to store them in Core Data, and retrieve them when ever necessary .

I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.

Set your Core Data property to transformable. Then use this extension:

extension NSObject {
    static func storeJSON(dataToStore: [String: AnyObject], completion: (data: NSData?) -> Void) {
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dataToStore, options: [])
            completion(data: data)
        } catch let error as NSError {
            print("NSJSONSerialization Error: \(error)")
            completion(data: nil)
        }
    }

    func retrieveJSON(completion: (json: JSON) -> Void) {
        if let data = self as? NSData {
            do {
                let nsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                completion(json: JSON(nsJSON))
            } catch let error as NSError {
                print("NSJSONSerialization Error: \(error)")
                completion(json: nil)
            }
        }
    }
}

If you don't use SwiftJSON then just use:

extension NSObject {
    static func storeJSON(dataToStore: [String: AnyObject], completion: (data: NSData?) -> Void) {
        do {
            let data = try NSJSONSerialization.dataWithJSONObject(dataToStore, options: [])
            completion(data: data)
        } catch let error as NSError {
            print("NSJSONSerialization Error: \(error)")
            completion(data: nil)
        }
    }

    func retrieveJSON(completion: (json: AnyObject?) -> Void) {
        if let data = self as? NSData {
            do {
                let nsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
                completion(json: nsJSON)
            } catch let error as NSError {
                print("NSJSONSerialization Error: \(error)")
                completion(json: nil)
            }
        }
    }
}

Example use with user.jsonTest as a transformable in core data:

func testThis() {
    makeSaveData() {
        self.user.jsonTest!.retrieveJSON() {
            json in
            print("json: \(json)")
        }
    }
}

func makeSaveData(completion: () -> Void) {
    var solarResourceDic: [String: String] = [:]
    var srDics: [[String: String]!] = []

    for i in 0..<5 {
        solarResourceDic = [:]
        solarResourceDic["system_capacity"] = "\(i)"
        solarResourceDic["azimuth"] = "\(i + 1)"
        solarResourceDic["tilt"] = "\(i + 2)"
        solarResourceDic["array_type"] = "\(i + 3)"
        solarResourceDic["module_type"] = "\(i + 4)"
        solarResourceDic["losses"] = "\(i + 5)"
        srDics.append(solarResourceDic)
    }
    let dic = ["Solar Resource": srDics]

    NSObject.storeJSON(dic) {
        data in
        if data != nil {
            self.user.jsonTest = data
            appDelegate.coreData.saveContext()
            completion()
        } else {
            print("Error storing data")
        }
    }
}

You can follow this great tutorial which shows how to save json to core data. In general you need to learn to things: how to parse a json feed (it will result to NSDictionaries with the parsed items) and how to save this dictionaries to your persistent store. This tutorial covers both.

I know this is old but there is a library called Sync which does json saving to DB

Sync eases your everyday job of parsing a JSON response and getting it into Core Data. It uses a convention-over-configuration paradigm to facilitate your workflow. Syncing JSON to Core Data is a repetitive tasks that often demands adding a lot of boilerplate code. Mapping attributes, mapping relationships, diffing for inserts, removals and updates are often tasks that don't change between apps. Taking this in account we took the challenge to abstract this into a library. Sync uses the knowledge of your Core Data model to infer all the mapping between your JSON and Core Data, once you use it, it feels so obvious that you'll wonder why you weren't doing this before.

Link:- Sync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM