0

I read a lot of docs about this but I can't really understand how it precisely works. I would like to save my apps data in JSON format on the disc of the phone.

I have a array of objects of this type:

@interface ObjectA : NSObject

@property (strong, nonatomic) NSMutableArray* names1;
@property (strong, nonatomic) NSMutableArray* names2;
@property (strong, nonatomic) NSMutableArray* names3;
@property (strong, nonatomic) NSMutableArray* names4;
@property (strong, nonatomic) NSString* nameObjectA;
@property (assign) int number;

By using JSONModel, how can I transforme a "NSMutableArray *ObjectA" in a JSON file and after that read this file back in the app.

Thanks.

- (id)initWithJSONDictionary:(NSDictionary *)jsonDictionary {
if(self = [self init]) {
    // Assign all properties with keyed values from the dictionary
    _nameObjectA = [jsonDictionary objectForKey:@"nameAction"];
    _number = [[jsonDictionary objectForKey:@"number"]intValue];

   _actions1 = [jsonDictionary objectForKey:@"Action1"];
    _actions2 = [jsonDictionary objectForKey:@"Action2"];
    _actions3 = [jsonDictionary objectForKey:@"Action3"];
    _actions4 = [jsonDictionary objectForKey:@"Action4"];


}

return self;

}

- (NSArray *)locationsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                     timeoutInterval:30.0];

// Get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

// Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

// Create a new array to hold the locations
NSMutableArray *actions = [[NSMutableArray alloc] init];

// Get an array of dictionaries with the key "actions"
NSArray *array = [jsonDictionary objectForKey:@"actions"];
// Iterate through the array of dictionaries
for(NSDictionary *dict in array) {
    // Create a new Location object for each one and initialise it with information in the dictionary
    Action *action = [[Action alloc] initWithJSONDictionary:dict];
    // Add the Location object to the array
    [actions addObject:action];
}

// Return the array of actions objects
return actions;

}

Jeks
  • 21
  • 5
  • How big is your data? 1GB? 10MB? – gran33 Sep 25 '14 at 12:14
  • Why do you want to use JSONModel? Why not NSJSONSerialization? – Hot Licks Sep 25 '14 at 12:19
  • @HotLicks JSONModel allows you to store non-JSON-compliant objects in your model, while NSJSONSerialization deals only with JSON-compliant objects. Maybe that's why? – Marin Todorov Sep 25 '14 at 12:40
  • No there is nothing special about my data. In the "NSMutableArray* names1,2,3,4",there is only strings. I decide to use JSONModel cause I read good things about it but maybe in my case it's just more easy to use only NSJSONSerialization. – Jeks Sep 25 '14 at 12:55

2 Answers2

2

The demo app that comes with JSONModel includes an example how to store your app's data via a JSONMOdel: https://github.com/icanzilb/JSONModel

Check the code in this view controller: https://github.com/icanzilb/JSONModel/blob/master/JSONModelDemo_iOS/StorageViewController.m

The logic is that you can export your model to a json string or json compliant dictionary and then save those to the disc using the standard APIs. Check the code

Marin Todorov
  • 6,377
  • 9
  • 45
  • 73
-1

In ObjectA you define two methods -- toDictionary and initWithDictionary. Roughly:

-(NSDictionary*) toDictionary {
    return @{@"names1":names1, @"names2":names2, @"names3":names3, @"names4":names4, @"nameObjectA":nameObjectA, @"number":@(number)};
}

- (id) initWithDictionary:(NSDictionary*) json {
    self = [super init];
    if (self) {
        self.names1 = json[@"names1];
        ... etc
        self.nameObjectA = json[@"nameObjectA"];
        self.number = json[@"number"].intValue;
    }
    return self;
}

Run the dictionary created by toDictionary through NSJSONSerialization to produce an NSData and write that to a file. To read, fetch the NSData from the file, run back through NSJSONSerialization, and use initWithDictionary.

Of course, this assumes that the contents of your dictionaries are "JSON legal" -- strings, numbers, NSArrays, or other NSDictionarys.

And, if the arrays/dictionaries being initialized are mutable, one should specify the "MutableContainers" option on NSJSONSerialization.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
  • I am not sure to understand when you say "this assumes that the contents of your dictionaries are JSON legal". Are you talking about the content of the NSMutableArray name1,name2... There is only strings inside. – Jeks Sep 25 '14 at 13:11
  • @user1622260 -That's what I'm talking about, and if they only contain strings they're fine. – Hot Licks Sep 25 '14 at 13:12
  • In the method: "initWithDictionary:(NSDictionary*) json" How is it possible to have self.names1 = json[@"names1"]; if names1 is a mutablearray ? – Jeks Sep 26 '14 at 17:57
  • @user1622260 - `json[@"names1"]` is an NSArray, and it will be a mutable one if you specify MutableContainers on NSJSONSerialization. – Hot Licks Sep 26 '14 at 19:05
  • toDictionary is working well. The Json file is well created but I have a problem with initWithDictionary. You can see my code. – Jeks Sep 26 '14 at 19:47
  • @user1622260 - On Stack Overflow never tell us you have a "problem" or a "crash". Be **specific** and provide **the exact and complete error/exception message** and the exception stack trace (if an exception). And in your listing identify the exact line where the error occurs. – Hot Licks Sep 27 '14 at 20:45