本文目錄一覽:
iOS post請求向服務器發送json格式數據(數組或字典)
1.字典
(ps usernames 是字段,jsonString是轉換json格式的字典)
2.數組
數組其實和字典一樣,只需將(dataWithJSONObject: dicFriends )參數,換成數組就可以了
ios 怎麼xcode製作json格式文件
創建工程後(這個就不說了吧,用過xcode的都清楚),算了–打開xcode後command+shift+n創建工程,工程名字自己起.
command + n 創建文件,我選的是 Swift File
回車自己起名字,然後在回車
4. 然後它會問你選哪個,當然選Use.json了,這不就完了嗎
iOS JSON轉字典
1.應用場景
接口傳輸數據時,有時需要用POST傳一長串string數據,一般要求轉為json格式方便服務器解析
2.需要轉義的字符說明及oc方法實現
NSString轉json時若包含以下字符,需要進行轉義
” (雙引號)
/ (正斜線)
\n (換行符)
\b (退格符)
\f (換頁符)
\r (回車符)
\t (製表符,一個tab或按8下空格)
oc方法如下
怎麼生成和解析iOS開發JSON格式數據
導語:JSON作為數據包格式傳輸的時候具有更高的效率,這是因為JSON不像XML那樣需要有嚴格的閉合標籤,這就讓有效數據量與總數據包比大大提升,從而減少同等數據流量的情況下,網絡的傳輸壓力。JSON 可以將 JavaScript 對象中表示的一組數據轉換為字符串,然後就可以在函數之間輕鬆地傳遞這個字符串,或者在異步應用程序中將字符串從 Web 客戶機傳遞給服務器端程序。這個字符串看起來有點兒古怪,但是JavaScript很容易解釋它,而且 JSON 可以表示比”名稱 / 值對”更複雜的結構。例如,可以表示數組和複雜的對象,而不僅僅是鍵和值的簡單列表。
怎麼生成和解析iOS開發JSON格式數據?
一、如何生成JSON格式的’數據?
1、利用字典NSDictionary轉換為鍵/值格式的數據。
// 如果數組或者字典中存儲了 NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他對象,就不能直接保存成文件了.也不能序列化成 JSON 數據.
NSDictionary *dict = @{@”name” : @”me”, @”do” : @”something”, @”with” : @”her”, @”address” : @”home”};
// 1.判斷當前對象是否能夠轉換成JSON數據.
// YES if obj can be converted to JSON data, otherwise NO
BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
if (isYes) {
NSLog(@”可以轉換”);
/* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8.
*/
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
/*
Writes the bytes in the receiver to the file specified by a given path.
YES if the operation succeeds, otherwise NO
*/
// 將JSON數據寫成文件
// 文件添加後綴名: 告訴別人當前文件的類型.
// 注意: AFN是通過文件類型來確定數據類型的!如果不添加類型,有可能識別不了! 自己最好添加文件類型.
[jsonData writeToFile:@”/Users/SunnyBoy/Sites/JSON_XML/dict.json” atomically:YES];
NSLog(@”%@”, [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
} else {
NSLog(@”JSON數據生成失敗,請檢查數據格式”);
}
2、通過JSON序列化可以轉換數組,但轉換結果不是標準化的JSON格式。
NSArray *array = @[@”qn”, @18, @”ya”, @”wj”];
BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
if (isYes) {
NSLog(@”可以轉換”);
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
[data writeToFile:@”/Users/SunnyBoy/Sites/JSON_XML/base” atomically:YES];
} else {
NSLog(@”JSON數據生成失敗,請檢查數據格式”);
}
二、如何解析JSON格式的數據?
1、使用TouchJSon解析方法:(需導入包:#import “TouchJson/JSON/CJSONDeserializer.h”)
//使用TouchJson來解析北京的天氣
//獲取API接口
NSURL *url = [NSURL URLWithString:@””];
//定義一個NSError對象,用於捕獲錯誤信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:error];
NSLog(@”jsonString—%@”,jsonString);
//將解析得到的內容存放字典中,編碼格式為UTF8,防止取值的時候發生亂碼
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:error];
//因為返回的Json文件有兩層,去第二層內容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@”weatherinfo”];
NSLog(@”weatherInfo—%@”,weatherInfo);
//取值打印
NSLog(@”%@”,[NSString stringWithFormat:@”今天是 %@ %@ %@ 的天氣狀況是:%@ %@ “,[weatherInfo objectForKey:@”date_y”],[weatherInfo objectForKey:@”week”],[weatherInfo objectForKey:@”city”], [weatherInfo objectForKey:@”weather1″], [weatherInfo objectForKey:@”temp1″]]);
2、使用SBJson解析方法:(需導入包:#import “SBJson/SBJson.h”)
//使用SBJson解析北京的天氣
NSURL *url = [NSURL URLWithString:@””];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:error];
NSDictionary *weatherInfo = [rootDic objectForKey:@”weatherinfo”];
NSLog(@”%@”, [NSString stringWithFormat:@”今天是 %@ %@ %@ 的天氣狀況是:%@ %@ “,[weatherInfo objectForKey:@”date_y”],[weatherInfo objectForKey:@”week”],[weatherInfo objectForKey:@”city”], [weatherInfo objectForKey:@”weather1″], [weatherInfo objectForKey:@”temp1″]]);
3、使用IOS5自帶解析類NSJSONSerialization方法解析:(無需導入包,IOS5支持,低版本IOS不支持)
// 從中國天氣預報網請求數據
NSURL *url = [ NSURL URLWithString:@””];
// 創建請求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 在網絡完成的 Block 回調中,要增加錯誤機制.
// 失敗機制處理: 錯誤的狀態碼!
// 最簡單的錯誤處理機制:
if (data !error) {
// JSON格式轉換成字典,IOS5中自帶解析類NSJSONSerialization從response中解析出數據放到字典中
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSDictionary *dict = obj[@”weatherinfo”];
NSLog(@”%@—%@”, dict, dict[@”city”]);
}
}] resume];
4、使用JSONKit的解析方法:(需導入包:#import “JSONKit/JSONKit.h”)
//如果json是“單層”的,即value都是字符串、數字,可以使用objectFromJSONString
NSString *json1 = @”{\”a\”:123, \”b\”:\”abc\”}”;
NSLog(@”json1:%@”,json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@”json1.a:%@”,[data1 objectForKey:@”a”]);
NSLog(@”json1.b:%@”,[data1 objectForKey:@”b”]);
//如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能會報錯(測試結果表明:使用由網絡或得到的php/json_encode生成的json時會報錯,但使用NSString定義的json字符串時,解析成功),最好使用objectFromJSONStringWithParseOptions:
NSString *json2 = @”{\”a\”:123, \”b\”:\”abc\”, \”c\”:[456, \”hello\”], \”d\”:{\”name\”:\”張三\”, \”age\”:\”32\”}}”;
NSLog(@”json2:%@”, json2);
NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@”json2.c:%@”, [data2 objectForKey:@”c”]);
NSLog(@”json2.d:%@”, [data2 objectForKey:@”d”]);
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/190828.html