iOS开发 NSString转JSON、NSDictionary和JSON互转

1.应用场景

接口传输数据时,有时需要用POST传一长串string数据,一般要求转为json格式方便服务器解析

  • 解释:以接口参数的形式上传复杂日志的内容(字符串),此复杂字符串做为接口参数值必须转成json字符串,否则接口上传失败。

2.需要转义的字符说明

  • NSString转json时若包含以下字符,需要进行转义
"  (双引号)
/  (正斜线)
\n (换行符)
\b (退格符)
\f (换页符)
\r (回车符)
\t (制表符,一个tab或按8下空格)
等

3. 普通字符串转json字符串的方法实现

方法一:直接根据特殊字符定制方法进行转换(不建议)

  • 网上常见使用如下方法进行string转jsonstring,对于一些简单的转换需求这个可以实现,但是对于复杂情况并不能实现完全转换。
- (NSString *)string2JSONString:(NSString *)string {
    NSMutableString *s = [NSMutableString stringWithString:string];
    [s replaceOccurrencesOfString:@"\"" withString:@"\\\"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"/" withString:@"\\/" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\n" withString:@"\\n" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\b" withString:@"\\b" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\f" withString:@"\\f" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\r" withString:@"\\r" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    [s replaceOccurrencesOfString:@"\t" withString:@"\\t" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [s length])];
    return [NSString stringWithString:s];
}

方法二:先自定义字典存入string,使用自带的JSONSerialization把字典转成json后,删除key只保留value部分即可(推荐)

  • 1.读取包含特殊字符的文本,存入字符串midiStr
    NSString *midiPath = [[NSBundle mainBundle] pathForResource:@"test11" ofType:@"txt"];
    NSFileHandle* readHandle = [NSFileHandle fileHandleForReadingAtPath:midiPath];
    [readHandle seekToFileOffset:0];
    NSData* data = [readHandle readDataToEndOfFile];
    NSString *midiStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  • 2.midiStr存入自定义字典,并转成jsonString
  • 3.拆分jsonDictString,仅取json键对应的value值部分,即midiStr转换为了json字符串。

oc写法

+ (NSString *)stringToJsonStrWithStr:(NSString *)str{
    NSString *key = @"json";
    
    NSDictionary *tempDict = @{key: str};
    
    NSMutableString *tempJsonStr = [[NSMutableString alloc] initWithString:[NSString jsonStringFromDict:tempDict]];
    
    NSString *valueJsonStr1 = [tempJsonStr substringFromIndex:key.length+5];
    
    NSString *valueJsonStr2 = [[[NSMutableString alloc] initWithString:valueJsonStr1] substringToIndex:valueJsonStr1.length-2];
    
    return valueJsonStr2;
}

swift写法

static func stringToJsonStr(str: String) -> String{
        
        let key = "json"
        let tempDict = [key: str]
        
        if(!JSONSerialization.isValidJSONObject(tempDict)) {
            print("无法解析出JSONString")
            return ""
        }
        
        
        do {
            let data = try JSONSerialization.data(withJSONObject: tempDict)
            let jsonStr = String(data: data, encoding: .utf8) ?? ""
            //去除键,只留转化的value
            let json1 = jsonStr.dropFirst(key.count+4)//"{\"json\":
            let json2 = json1.dropLast(1)
            
            return String(json2)
        } catch let error as NSError {
            print(error)
            return ""
        }
    }

4. 字典和json互转方法实现

4-1 字典转JSON

  • OC 方法实现
- (NSString *)convert2JSONWithDictionary:(NSDictionary *)dic{
    NSError *err;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&err];
    
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",err);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSLog(@"%@",jsonString);
    return jsonString;
}
  • swift方法实现
public static func convertDictionaryToString(dict:[String:AnyObject]) -> String {
        var result:String = ""
        do {
          //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
          let jsonData = try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.init(rawValue: 0))
       
          if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
            result = JSONString
          }
       
        } catch {
          result = ""
        }
        return result
    }

4-2 JSON转字典

  • OC 方法实现
- (NSDictionary *)convert2DictionaryWithJSONString:(NSString *)jsonString{
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"%@",err);
        return nil;
    }
    return dic;
}

  • swift 实现方法
static func convertStringToDictionary(text: String) -> [String:AnyObject]? {
        if let data = text.data(using: String.Encoding.utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: [JSONSerialization.ReadingOptions.init(rawValue: 0)]) as? [String:AnyObject]
                
            } catch let error as NSError {
                Log.error(error)
            }
        }
        return nil
    }

4-3 数组转json(同字典转json)

  • swift
    static func convertArrayToString(arr:[AnyObject]) -> String {
        var result:String = ""
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: arr, options: JSONSerialization.WritingOptions.init(rawValue: 0))
            if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
                result = JSONString
                
            }
            
        } catch {
            result = ""
            
        }
        return result
    }

5. 附场景应用:读取文本文件内容POST方法上传,参数放在body内

- (void)uploadJsonStringAsyn{
    //读取txt文件内容(包含回车空格等特殊字符)转为jsonString
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    NSString *midiPath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"txt"];
    NSFileHandle* readHandle = [NSFileHandle fileHandleForReadingAtPath:midiPath];
    [readHandle seekToFileOffset:0];
    NSData* data = [readHandle readDataToEndOfFile];
    NSString *midiStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    params[@"jsonString"] = [self stringToJsonStr:midiStr];
    
    //设置上传地址
    NSString *urlString = [NSString stringWithFormat:@"http://"];
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    //添加参数
    [request setHTTPBody:jsonData];
    
    //创建session对象
    NSURLSession *session = [NSURLSession sharedSession];
    
    //创建一个请求任务
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *result = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"POST%@",result);
    }];
    
    [task resume];
}

你可能感兴趣的:(iOS开发 NSString转JSON、NSDictionary和JSON互转)