美文网首页
iOS开发 NSString转JSON、NSDictionary

iOS开发 NSString转JSON、NSDictionary

作者: Jesscia_Liu | 来源:发表于2019-01-15 11:31 被阅读0次

    1.应用场景

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

    2.需要转义的字符说明及oc方法实现

    • NSString转json时若包含以下字符,需要进行转义
    "  (双引号)
    /  (正斜线)
    \n (换行符)
    \b (退格符)
    \f (换页符)
    \r (回车符)
    \t (制表符,一个tab或按8下空格)
    
    
    • oc方法如下
    - (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];
    }
    

    3.读取文本文件内容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 string2JSONString: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];
    }
    

    4.iOS字典(NSDictionary)和JSON字符串之间互转

    注意: 若midiStr是字典中键对应值,无需调用string2JSONString:

        NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
        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];
        params[@"info"] = midiStr;
    
        NSString *jsonString = [self convert2JSONWithDictionary:params];
        [self convert2DictionaryWithJSONString:jsonString];
    
    4-1 字典转JSON
    - (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;
    }
    
    4-2 JSON转字典
    - (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;
    }
    
    

    相关文章

      网友评论

          本文标题:iOS开发 NSString转JSON、NSDictionary

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