iOS NSDictionary、NSData、JSON数据类型相互转换
iOS NSDictionary、NSData、JSON数据类型相互转换
iOS经常需要用到数据类型的转换,下面列举一下常用类型的转换。
1.NSDictionary类型转换为NSData类型:
[cpp] view plaincopy
//NSDictionary -> NSData:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
@"balance", @"key",
@"remaining balance", @"label",
@"45", @"value",
@"USD", @"currencyCode",nil];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:params forKey:@"Some Key Value"];
[archiver finishEncoding];
2.NSData类型转换为NSDictionary类型:
[cpp] view plaincopy
//NSData -> NSDictionary
NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];
3.NSDictionary类型转换为JSON数据类型:
[cpp] view plaincopy
//NSDictionary -> JSON:
NSString *jsonStr=[dict JSONRepresentation];
注意JSON与NSDictionary类型的转换一般会用到第三方公开的JSON库,读者可以在网上找到很多。
上一篇:没有了
下一篇:苹果iphone IOS8提示更新了,我需要更新吗?
讨论数量:0