[英]Copying JSON response dictionary to plist
我有一個包含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時間)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.