3

我有一个包含 JSON 响应和 plist 文件的字典。我想用 JSON 响应值更新我的 plist 文件中的值。我该怎么做?

4

2 回答 2

8

这就是我所做的,我现在正在努力,但我到了那里:


JSON到字典:

NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSLog(@"%@",jsonString);

NSArray *result = [jsonString JSONValue];

for(NSDictionary *dictionary in result){
    return dictionary; //if you are getting more then one row, do something here
}

保存字典:

id plist = plistDict;

NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"Data.plist"];
NSLog(@"%@",plistPath);

NSData *xmlData;
NSString *error;

xmlData = [NSPropertyListSerialization dataFromPropertyList:plist
                                                     format:NSPropertyListXMLFormat_v1_0
                                           errorDescription:&error];
if(xmlData) {
    if ([xmlData writeToFile:plistPath atomically:YES]) {
        NSLog(@"Data successfully saved.");
    }else {
        NSLog(@"Did not managed to save NSData.");
    }

}
else {
    NSLog(@"%@",errorDesc);
    [error release];
}
}

如果要更新值,我会说您应该打开 plist,将其放入字典中,更新字典中的值,然后再次将字典保存到 plist。

希望这可以帮助。

于 2009-11-28T13:01:59.287 回答
1

如果您在 Mac OS X 10.7 或 iOS 5 下工作,有一个名为 NSJSONSerialization 的 Foundation 类将读取/写入 JSON 文件。将 JSON 转换为 plist 将非常简单:(暗示您启用了 ARC 或 GC)

NSString *infile = @"/tmp/input.json"
NSString *oufile = @"/tmp/output.plist"

[[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:infile]
                                 options:0
                                   error:NULL] writeToFile:oufile
                                                atomically:YES];

然而,从 plist 到 JSON 的转换会更麻烦,因为 NSDate 和 NSData 对象不能出现在 JSON 中。您可能需要检查文件的内容并以另一种方式存储 NSData 和 NSDate(例如 NSData 作为 Base-64 字符串,NSDate 作为它们的 UNIX 时间)

于 2012-06-06T03:17:44.417 回答