[iOS]字典与字符串的相互转换

2022-07-08  本文已影响0人  汴城码农
+ (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 *)stringWithDictionary:(NSDictionary *)dictionary {
    if (dictionary == nil) {
        return nil;
    }
    
    NSError * err;
    NSData * jsonData = [NSJSONSerialization  dataWithJSONObject:dictionary options:0 error:&err];
    NSString * myString = [[NSString alloc] initWithData:jsonData   encoding:NSUTF8StringEncoding];
    NSLog(@"%@",myString);
      
    if(err) {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return myString;
}
上一篇下一篇

猜你喜欢

热点阅读