美文网首页
字典转 Json , json ->dic

字典转 Json , json ->dic

作者: 失忆的程序员 | 来源:发表于2017-08-24 13:29 被阅读162次

    /**

    * @brief 把格式化的JSON格式的字符串转换成字典

    * @param jsonString JSON格式的字符串

    * @return 返回字典

    */

    //  json格式字符串转字典:

    - (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

    if (jsonString == nil) {

    return nil;

    }

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

    NSError *err;

    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];

    if (err) {

    NSLog(@"json解析失败:%@",err);

    return nil;

    }

    return dic;

    }

    // 字典转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 *)convertToJsonData:(NSDictionary *)dict{

    NSError *error;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString *jsonString;

    if (!jsonData) {

    NSLog(@"%@",error);

    }else{

    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    }

    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];

    NSRange range = {0,jsonString.length};

    //去掉字符串中的空格

    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];

    NSRange range2 = {0,mutStr.length};

    //去掉字符串中的换行符

    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];

    //替换掉网址的\转义    \/  替换为 /

    [mutStr replaceOccurrencesOfString:@"\\/" withString:@"/" options:NSLiteralSearch range:NSMakeRange(0,mutStr.length)];

    return mutStr;

    }

    方法一图片 方法二图片

    相关文章

      网友评论

          本文标题:字典转 Json , json ->dic

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