美文网首页工作生活
iOS 数组转json串、json串转数组

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

作者: 差不多先生__ | 来源:发表于2019-07-01 14:49 被阅读0次

    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串转数组

        本文链接:https://www.haomeiwen.com/subject/tougcctx.html