美文网首页
NSDictionary JSON String互转

NSDictionary JSON String互转

作者: 霜之幽语 | 来源:发表于2018-01-29 16:26 被阅读601次

    NSDictionary转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];
    
        return mutStr;
    }
    

    JSON转NSDictionary

    + (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;
    }
    

    相关文章

      网友评论

          本文标题:NSDictionary JSON String互转

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