satyanarayana
satyanarayana

Reputation: 275

Using CoreData to store JSON string

I have a set of JSON strings where each JSON string will have a key. Now, I want to store these JSON strings on device so that I can use this data later. Here I do not store any objects on device. Can I use CoreData or is there any alternative to this? What is the best practice to store JSON on device?

Upvotes: 0

Views: 812

Answers (3)

Anupdas
Anupdas

Reputation: 10201

If you don't have much data to store you can use plist or json. Plist would be more easier, if you store json as such you need a couple of more lines of code.

Create a DataHelper class with methods to save,add , findAll, findFirtWithValue:forObject: in it.

Here is a sample

#define kPlistFilePath @"Data.plist"
#define kJsonFilePath @"Data.json"

@implementation DataController

+ (NSString *)savedFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = paths[0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:kPlistFilePath];
    return filePath;
}

+ (NSArray *)findAll
{   
    NSString *filePath = [self savedFilePath];
    return [NSArray arrayWithContentsOfFile:filePath];
}

+ (void)saveJSON:(id)object 
{
    NSString *filePath = [self savedFilePath];

    NSArray *unsavedArray = nil;

    if ([object isKindOfClass:[NSString class]]) {
        NSError *error = nil;
        unsavedArray = [NSJSONSerialization JSONObjectWithData:[object dataUsingEncoding:NSUTF8StringEncoding]
                                                       options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
                                                         error:&error];

    }else if([object isKindOfClass:[NSArray class]]){
        unsavedArray = object;

    }else if([object isKindOfClass:[NSDictionary class]]){
        unsavedArray = @[object];
    }

    if ([unsavedArray count]) {
        [unsavedArray writeToFile:filePath atomically:NO];
    }
}



+ (NSDictionary *)userInfoForID:(NSString *)userID
{
    NSArray *allData = [self findAll];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userid = %@",userID];
    return [[allData filteredArrayUsingPredicate:predicate]lastObject];
}

Upvotes: 0

paulmelnikow
paulmelnikow

Reputation: 17208

You can also simply save your JSON to a file and deserialize it again when you need it next.

Upvotes: 1

strong
strong

Reputation: 131

JSON just define the compact data format for fast transfer between server and client (your App).

What's you need to do is decode the JSON data from server to data type NSDictionary, NSArray, NSString... and then if you want to store them use plist, sqlite or CoreData to store.

For CoreData, you need to create Entity associate with JSON format.

Ex: "key":"value" -> NSDictionary

Upvotes: 0

Related Questions