方法总是重写json文件

时间:2016-01-28 14:11:20

标签: objective-c json macos

NSURL *url = [NSURL URLWithString:@"file://localhost/Users/admin/Desktop/JSON/vivijson.json"];
    NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:self.loginString, @"login",
                                                                    self.nameString, @"name",
                                                                    self.lastNameString, @"lastName",
                                                                    self.emailString, @"email",
                                                                    self.numberString, @"number",  nil];
    NSError *error;
    NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
    [regMutArray addObject:regDict];
    NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:regMutArray options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
    [jsonConvRegArrayData writeToURL:url atomically:YES];

此方法正在重写JSON,并重新启动它,但我需要在我的JSON中添加一些。

1 个答案:

答案 0 :(得分:1)

您应该首先使用JSONObjectWithData将现有的JSON读入可变数组,并使用NSJSONReadingMutableContainers作为读取选项。然后将新数组元素添加到JSONObjectWithData返回的可变数组中,然后使用dataWithJSONObject将其转换回JSON

这是代码。

   NSURL *url = [NSURL URLWithString:@"file://localhost/Users/Shared/vivijson.json"];
    NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:@"self.loginString, @"login",
                             self.nameString, @"name",
                             self.lastNameString, @"lastName",
                             self.emailString, @"email",
                             self.numberString, @"number",  nil];
    NSError *error;
    NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
    [regMutArray addObject:regDict];

    NSData *data = [NSData dataWithContentsOfURL:url];
    NSMutableArray *array = nil;
    if (data)
        array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if (array == nil)
    {
        array = [[NSMutableArray alloc] init];
    }
    [array addObjectsFromArray:regMutArray];

    NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
    [jsonRegString writeToURL:url atomically:true encoding:NSUTF8StringEncoding error:nil];