iOS NSDictionary、NSData、JSON資料類型相互轉換
iOS經常需要用到資料類型的轉換,下面列舉一下常用類型的轉換。
1.NSDictionary類型轉換為NSData類型:
//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類型:
//NSData -> NSDictionaryNSData *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資料類型:
//NSDictionary -> JSON:NSString *jsonStr=[dict JSONRepresentation];
注意JSON與NSDictionary類型的轉換一般會用到第三方公開的JSON庫,讀者可以在網上找到很多。