简体   繁体   中英

Best way to store JSON data in to Core Data

I'm new to Core data and was wondering which was the best way to store a Json Data like this :

{"LG" : 
      { "Nexus 5" :
                  { "variant"s : [
                                  {"model" : "Nexus 5 16gb"},
                                  {"model" : "Nexus 5 32gb"}
                                 ]
                  },
      },
      { "Nexus 4" :
                  { "variant"s : [
                                  {"model" : "Nexus 4 16gb"},
                                  {"model" : "Nexus 4 32gb"}
                                 ]
                  },
      },
}, ...... so on..

I tried storing the whole data as a NSDictionary , after making the Attribute Type "Transformable" , but I encountered some errors such as NSUnknownKeyException .

I would like to store the data as NSString and make use of some Relationships .

Can someone tell me what might be the best way to store the same and not saving the whole bunch of data as an NSDictionary ?

My two cents.

Brand <-->> Model <-->> Variant

where Brand will contain LG, etc., Model will contain Nexus 4, etc. and Variant will contain Nexus 5 16GB, etc.

Brand has a to many relationships with Model . Model has a to many relationship with Variant .

Please refer to my prev answer on how to set up a to many relationship: Setting up a parent-child relationship in Core Data .

Anyway you should Apple doc and google a little bit. You can find a lot of materials out of there (eg Core Data from Scratch: Relationships and More Fetching ).

I'd recommend reading up about Core Data and about relational databases in general, to avoid getting a design that might be absolute rubbish. The Core Data model should be at the centre of everything. That's what you need to design.

How you receive data in JSON is very secondary. Ignore JSON completely for the moment. First you need to get the database design right. Once you've got that, putting the things that are delivered to you through JSON is quite simple.

I'd have a table "Variant" which currently just has a variant with a string for the name, like "Nexus 5 16gb". Then I'd have a table "phone" with a relation to the manufacture, a string for the name, and a one-to-many relation for the "Variant". Then I'd have a table "manufacturer", with a string for the name, and a one-to-many relation for the "Phones".

best way? don't store json as a string!

translate the json into a valid object graph while parsing

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