JSON字符串与数组,字典互相转换

数组/字典转字符串

- (NSString *)arrayToJSONString:(NSArray *)array {
    if (array != nil || array.count > 0) {
        NSError *error;
        NSData *data=[NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        if (error != nil) return @"error";
        return jsonStr;
    }
    return @"";
}

字符串转数组/字典

- (NSArray *)jsonToArray:(NSString *)jsonString {
    
    if (jsonString != nil && jsonString.length > 0) {
        NSData* data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        __autoreleasing NSError* error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        if (error != nil) return nil;
        return result;
    }
    return @[];
}

你可能感兴趣的:(JSON字符串与数组,字典互相转换)