我有一个包含JSON响应和plist文件的字典。 我想使用JSON响应值更新我的plist文件中的值。 我该如何做?
这是我所做的,现在正在努力完成,但我已经接近成功:
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中。
希望这可以帮助您。
如果您正在使用 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时间)。