1

I am stuck trying to save y data from core data into a json file.

Can anyone give hints about the best way to do this? Perhaps a tutorial.

Thanks.

EDIT: I'd like to store my data in json file in the app directory. SO that latter I could export it into iCloud for example. I couldn't find much about creating a json file... Strange is that for reading a json file I found plenty....

4
  • What's your issue? Is your issue about saving an entity with CoreData or just particularly the JSON file? You can save it as (NS)Data, (NS)String if you want, or save it in the drive, and just store the path. Commented Nov 29, 2016 at 16:18
  • I Edited my question The issue is about creating a json file with the data Commented Nov 29, 2016 at 16:23
  • JSON file is just a file. You can save it with (NS)Data or (NS)String methods, and just read it correctly then. Look at writeToFile:atomically: (from NSData), or writeToFile:atomically:encoding:error: (from NSString). Commented Nov 29, 2016 at 16:25
  • Ok. but lets say I have image, strings and doubles in my data (coredata). Can I store everything in a file (json) with writetoFile:atomically? (afterwards I want to reload it again) Commented Nov 29, 2016 at 16:53

2 Answers 2

2

It seems like it would be a lot of trouble to store files in JSON if they are already persisted in CoreData, especially since if you are using Cloudkit, you will not be uploading the files in JSON format. I think you could accomplish what you want though by first creating a dictionary for your objects:

let messageDic = ["message": "Hello Motto"]

and then serialize the dictionary in JSON:

 do {
        let messageData = try JSONSerialization.data(withJSONObject: messageDic, options: .prettyPrinted)

    } catch {
            print("error with serialization")
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I am using this, in my project. This function returns json string formatted data which is easily saved into coredata. Above method is also correct but this method produce json formatted string file which is easily save into coredata. Hope it will work for you.

 func convertAnyobjectToJSON(anyObject: AnyObject) -> JSON{
        let jsonData = try! JSONSerialization.data(withJSONObject: anyObject, options: JSONSerialization.WritingOptions.prettyPrinted)
        let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
        if let dataFromString = jsonString.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            let json = JSON(data: dataFromString)
            return json
        }
        return nil
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.