1. 字符串与NSData
//NSString -> NSData
NSData *data = [@"520it.com" dataUsingEncoding:NSUTF8StringEncoding];
- 将NSData转换为NSDatastring字符串
//NSData -> NSString
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
2. 字符串与数组
NSArray *array = [str componentsSeparatedByString:@"-"];//其中"-"号为分隔符
NSString *str = [array componentsJoinedByString:@"-"];//其中"-"号为分隔符
3. 字符串与字典
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json解析失败:%@",err);
return nil;
}
return dic;
}
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}