Json 字符串和字典,数组的转化

2019-08-13  本文已影响0人  月沉眠love

1.根据Json字符串返回Dictionary

//根据Json字符串返回Dictionary
+(NSDictionary *)stringTransformationDictionaryByJsonString:(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;
}

2.根据Json字符串返回NSArray

//根据Json字符串返回NSArray
+(NSArray *)stringTransformationArrayByJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *arr = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return arr;
}

3.根据Dictionary返回Json字符串

//根据Dictionary返回Json
+(NSString*)dictionaryTransformationJsonStringByDictionary:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    if (parseError) {
        return nil;
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

4.根据NSArray返回Json字符串

//根据NSArray返回Json字符串
+(NSString*)arrayTransformationJsonStringByArray:(NSArray *)arr{
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
    if (parseError) {
        return nil;
    }
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
上一篇下一篇

猜你喜欢

热点阅读