我有一个包含JSON响应和plist文件的字典。我想用JSON响应值更新plist文件中的值。我该怎么做?
答案 0 :(得分:8)
这就是我所做的,我现在正在努力,但我到了那里:
JSON to dictionary:
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中。
希望这有帮助。
答案 1 :(得分: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时间)