我阅读了很多关于此的文档,但我无法真正理解它是如何工作的。我想将我的应用程序数据以 JSON 格式保存在手机的光盘上。
我有一个这种类型的对象数组:
@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;
通过使用 JSONModel,我如何在 JSON 文件中转换“NSMutableArray *ObjectA”,然后在应用程序中读取该文件。
谢谢。
- (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;
}