iOS-JSON字符串转NSDictionary / 字典转JSON字符串

/** * JSON字符串转NSDictionary * *  @param jsonString JSON字符串 * *  @return NSDictionary */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        NSLog(@"json解析失败:%@",error);
        return nil;
    }
    return dic;
}
/** * 字典转JSON字符串 * *  @param dic 字典 * *  @return JSON字符串 */
+ (NSString*)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

你可能感兴趣的:(json,NSString,ios开发)