1.應(yīng)用場景
接口傳輸數(shù)據(jù)時,有時需要用POST傳一長串string數(shù)據(jù),一般要求轉(zhuǎn)為json格式方便服務(wù)器解析
- 解釋:以接口參數(shù)的形式上傳復(fù)雜日志的內(nèi)容(字符串)糖赔,此復(fù)雜字符串做為接口參數(shù)值必須轉(zhuǎn)成json字符串萍丐,否則接口上傳失敗。
2.需要轉(zhuǎn)義的字符說明
- NSString轉(zhuǎn)json時若包含以下字符,需要進行轉(zhuǎn)義
" (雙引號)
/ (正斜線)
\n (換行符)
\b (退格符)
\f (換頁符)
\r (回車符)
\t (制表符,一個tab或按8下空格)
等
3. 普通字符串轉(zhuǎn)json字符串的方法實現(xiàn)
方法一:直接根據(jù)特殊字符定制方法進行轉(zhuǎn)換(不建議)
- 網(wǎng)上常見使用如下方法進行string轉(zhuǎn)jsonstring放典,對于一些簡單的轉(zhuǎn)換需求這個可以實現(xiàn)逝变,但是對于復(fù)雜情況并不能實現(xiàn)完全轉(zhuǎn)換。
- (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把字典轉(zhuǎn)成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存入自定義字典弥臼,并轉(zhuǎn)成jsonString
- 3.拆分jsonDictString宴咧,僅取json鍵對應(yīng)的value值部分,即midiStr轉(zhuǎn)換為了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) ?? ""
//去除鍵掺栅,只留轉(zhuǎn)化的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互轉(zhuǎn)方法實現(xiàn)
4-1 字典轉(zhuǎn)JSON
- OC 方法實現(xiàn)
- (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方法實現(xiàn)
public static func convertDictionaryToString(dict:[String:AnyObject]) -> String {
var result:String = ""
do {
//如果設(shè)置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轉(zhuǎn)字典
- OC 方法實現(xiàn)
- (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 實現(xiàn)方法
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 數(shù)組轉(zhuǎn)json(同字典轉(zhuǎn)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. 附場景應(yīng)用:讀取文本文件內(nèi)容POST方法上傳,參數(shù)放在body內(nèi)
- (void)uploadJsonStringAsyn{
//讀取txt文件內(nèi)容(包含回車空格等特殊字符)轉(zhuǎn)為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];
//設(shè)置上傳地址
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];
//添加參數(shù)
[request setHTTPBody:jsonData];
//創(chuàng)建session對象
NSURLSession *session = [NSURLSession sharedSession];
//創(chuàng)建一個請求任務(wù)
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];
}