Original http://blog.sina.com.cn/s/blog_6b8c3d7a01018803.html
First, the introduction of Jsonkit
NSString *str =Nil; //stringNsmutablestring *string=[[Nsmutablestring alloc] init]; [stringAppendString:@"xxxx"]; STR= [stringjsonstring]; NSLog (@"str1:%@", [NSString stringwithstring:str]); //ArrayNsarray *array = [[Nsarray alloc] Initwithobjects:@"111",@"333",@"222", nil]; //Nsmutablearray *array = [Nsmutablearray array];str =[Array jsonstring]; NSLog (@"str2:%@", [NSString stringwithstring:str]); [Array release]; //DictionaryNsarray *firstarr = [Nsarray arraywithobjects:@" First",@"Second", nil]; //basic data type converted to NSNumber typeNsarray *secondarr = [Nsarray arraywithobjects:[nsnumber numberwithdouble:2.1],[nsnumber Numberwithbool:no], nil]; //Add to DictionaryNsdictionary *dic = [Nsdictionary Dictionarywithobjectsandkeys:firstarr,@" First", Secondarr,@"Second", nil]; //Convert to JSON formatstr =[dic jsonstring]; NSString*STR2 =[NSString Stringwithstring:str]; NSLog (@"str3:%@", STR2); //CodingNSData *archive =[Nskeyedarchiver Archiveddatawithrootobject:array]; //NSLog (@ "archive:%@", archive);Nsarray *ARR2 =[Nskeyedunarchiver unarchiveobjectwithdata:archive]; NSLog (@"arr2:%@", ARR2);
Second, the system comes with
//move array to JSON-(NSData *) Tojsondata: (ID) thedata{Nserror*error =Nil; NSData*jsondata =[Nsjsonserialization datawithjsonobject:thedata options:nsjsonw ritingprettyprinted Error:&ERROR]; if([Jsondata length] >0&& Error = =Nil) { returnJsondata; }Else{ returnNil; }}nsstring*jsonstring =[[NSString alloc] Initwithdata:jsondata encoding:nsutf8stringencoding];