iOS中NSString,NSData和char的相互转换,JSON串转化为NSDictionary或NSArray

 1.NSString 转换成NSData 对象

NSData* xmlData = [@"testdata" dataUsingEncoding:NSUTF8StringEncoding]; 

2.NSData 转换成NSString对象

NSData * data; 
NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];

3.NSData 转换成char* 

NSData *data; 
char *test=[data bytes]; 

4.char* 转换成NSData对象

byte* tempData = malloc(sizeof(byte)*16); 
NSData *content=[NSData dataWithBytes:tempData length:16];

5.将JSON串转化为NSDictionary或NSArray

    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];

6.将NSDictionary或NSArray转化为JSON串

 NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

附:如果类型出现错误:便会出现这种类型的错误:

posted @ 2015-10-15 19:56  墨VS雪  阅读(942)  评论(0编辑  收藏  举报