iOS 数组转json串、json串转数组

1.数组格式的json串转成数组

- (NSArray *)toArrayWithJsonStr:(NSString *)jsonStr
{
    if ([jsonStr isKindOfClass:[NSArray class]]) {
        return (NSArray *)jsonStr;
    }
    if (jsonStr == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *resultArr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                   options:NSJSONReadingMutableContainers
                                                     error:&err];
    if(err) {
        NSLog(@"json解析失败:%@",err);
        return nil;
    }
    return resultArr;
}

2.数组转成json串

- (NSString *)toJsonStrWithArray:(NSArray *)arr {
    if ([arr isKindOfClass:[NSString class]]) {
        return (NSString *)arr;
    }
    NSError *parseError = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    jsonStr = [jsonStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    if (parseError) {
        jsonStr = @"";
    }
    return jsonStr;
}

字典与json串的相互转换

你可能感兴趣的:(iOS 数组转json串、json串转数组)