NSDictionary转换成JSON字符串

普通情况下,你可能会用一个NSDictionary的分类去做NSDictionary转JSON,如下代码:

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
if (! jsonData) {
    return @"{}";
} else {
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

然而,NSDictionary装的数据类型鱼龙混杂,有可能是NSDateNSNumberNSValue等Objective-C对象,而[NSJSONSerialization dataWithJSONObject:options:error:]这个方法是不能解析这些对象的,如果有这些对象,则会导致crash。所以我们应该在调用NSJSONSerialization之前加一步,将所有数据处理成NSString,代码如下:

NSError *error = nil;
NSData *jsonData = nil;
if (!self) {
    return nil;
}
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
    NSString *keyString = nil;
    NSString *valueString = nil;
    if ([key isKindOfClass:[NSString class]]) {
        keyString = key;
    }else{
        keyString = [NSString stringWithFormat:@"%@",key];
    }

    if ([obj isKindOfClass:[NSString class]]) {
        valueString = obj;
    }else{
        valueString = [NSString stringWithFormat:@"%@",obj];
    }

    [dict setObject:valueString forKey:keyString];
}];
jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if ([jsonData length] == 0 || error != nil) {
    return nil;
}
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;

这样就NSDictionary转JSON就不会crash了,同理,NSArray也应该这样做。

posted @ 2018-05-16 17:14  sundaysios  阅读(1126)  评论(0编辑  收藏  举报