iOS 字典转json串,json串转字典

1.json串转字典

- (NSDictionary *)toDictionaryWithJsonString:(NSString *)jsonStr {
    
    if ([jsonStr isKindOfClass:[NSDictionary class]]) {
        return (NSDictionary *)jsonStr;
    }
    NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                               options:NSJSONReadingMutableContainers
                                                                 error:&err];
    return resultDic;
}

2.字典转json串

- (NSString *)toJsonStrWithDictionary:(NSDictionary *)dict {
    if ([dict isKindOfClass:[NSString class]]) {
        return (NSString *)dict;
    }
    NSError *parseError = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonSrt = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (parseError) {
        jsonSrt = @"";
    }
    return jsonSrt;
}

json串与数组之间的相互转换

你可能感兴趣的:(iOS 字典转json串,json串转字典)