NSJSONSerialization 包含了以下五个类函数
+ (BOOL)isValidJSONObject:(id)obj;
判断 该实例(obj)是否为JSONObject
需满足下面三个条件
1.obj 是NSArray 或 NSDictionay 以及他们派生出来的子类
2.obj 包含的所有对象是NSString,NSNumber,NSArray,NSDictionary 或NSNull
3.NSNumber的对象不能是NaN或无穷大
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
将JSONObject的实例转成NSData
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
将NSData类型的实例转成JSONObject
+ (NSInteger)writeJSONObject:(id)obj toStream:(NSOutputStream *)stream options:(NSJSONWritingOptions)opt error:(NSError **)error;
将一个JSONObject的实例写入到一个输出流中 返回写入的长度
+ (id)JSONObjectWithStream:(NSInputStream *)stream options:(NSJSONReadingOptions)opt error:(NSError **)error;
从输入流中读取成JSONObject 并返回
- SMutableDictionary*dictionary=[[NSMutableDictionaryalloc]init];
- [dictionarysetValue:@"xiaominfc"forKey:@"username"];
- [dictionarysetValue:@"1991-03-26"forKey:@"birthday"];
- [dictionarysetValue:[NSNumbernumberWithInteger:23]forKey:@"age"];
- NSArray*arrayOfAnthonysChildren=[[NSArrayalloc]initWithObjects:@"Java",@"Objective-C",@"Python",@"C++",nil];
- [dictionarysetValue:arrayOfAnthonysChildrenforKey:@"program_language"];
- if([NSJSONSerializationisValidJSONObject:dictionary]){
- NSLog(@"itisaJSONObject!");
- }
- //usedataWithJSONObjectfun
- NSError*error=nil;
- NSData*jsonData=[NSJSONSerializationdataWithJSONObject:dictionaryoptions:NSJSONWritingPrettyPrintederror:&error];
- if([jsonDatalength]>0&&error==nil){
- NSString*jsonString=[[NSStringalloc]initWithData:jsonDataencoding:NSUTF8StringEncoding];
- NSLog(@"data:%@",jsonString);
- //useJSONObjectWithDatafun
- NSString*jsonDataString=@"{\"username\":\"xiaominfc\",\"city\":\"深圳\"}";
- NSData*data=[jsonDataStringdataUsingEncoding:NSUTF8StringEncoding];
- idjsonObject=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:&error];
- if([jsonObjectisKindOfClass:[NSDictionaryclass]]){
- NSDictionary*jsonDictionary=(NSDictionary*)jsonObject;
- NSLog(@"username:%@Andcity:%@",[jsonDictionaryvalueForKey:@"username"],[jsonDictionaryvalueForKey:@"city"]);
- //usewriteJSONObjectfun
- NSString*filePath=@"/Users/xiaominfc/text.txt";
- NSOutputStream*outStream=[[NSOutputStreamalloc]initToFileAtPath:filePathappend:NO];
- [outStreamopen];
- NSIntegerlength=[NSJSONSerializationwriteJSONObject:dictionarytoStream:outStreamoptions:NSJSONWritingPrettyPrintederror:&error];
- NSLog(@"write%ldbytes",(long)length);
- [outStreamclose];
- //useJSONObjectWithStream
- NSInputStream*inStream=[[NSInputStreamalloc]initWithFileAtPath:filePath];
- [inStreamopen];
- idstreamObject=[NSJSONSerializationJSONObjectWithStream:inStreamoptions:NSJSONReadingAllowFragmentserror:&error];
- if([streamObjectisKindOfClass:[NSDictionaryclass]]){
- NSDictionary*jsonDictionary=(NSDictionary*)streamObject;
- NSNumber*ageNumber=(NSNumber*)[jsonDictionaryvalueForKey:@"age"];
- NSLog(@"username:%@Andage:%d",[ageNumberintValue]);
- [inStreamclose];