本文目錄一覽:
- 1、iOS中JSON數據的解析
- 2、ios開發中,帶小括弧的JSON怎麼解析
- 3、在ios中json數據怎麼解析
- 4、iOS開源JSON解析庫MJExtension
- 5、怎麼生成和解析iOS開發JSON格式數據
iOS中JSON數據的解析
NSJSONSerialization提供了JSON數據封包、JSON數據解析,NSJSONSerialization將JSON數據轉換為NSDictionary或NSArray解包方法,將NSDictionary、NSArray對象轉換為JSON數據(可以通過調用isValidJSONObject來判斷NSDictionary、NSArray對象是否可以轉換為JSON數據)封包。
NSJSONSerialization Class Reference
ios開發中,帶小括弧的JSON怎麼解析
使用 IOS5自帶解析類NSJSONSerialization方法解析:(無需導入包,IOS5支持,低版本IOS不支持)
– (void)btnPressIOS5Json:(id)sender {
NSError *error;
//載入一個NSURL對象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@””]];
//將請求的url數據放到NSData對象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//IOS5自帶解析類NSJSONSerialization從response中解析出數據放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@”weatherinfo”];
NSString *detail = [NSString stringWithFormat:@”今天是 %@ %@ %@ 的天氣狀況是:%@ %@ “,[weatherInfo objectForKey:@”date_y”]
,[weatherInfo objectForKey:@”week”],[weatherInfo objectForKey:@”city”],[weatherInfo objectForKey:@”weather1″]
,[weatherInfo objectForKey:@”temp1″]];
NSLog(@”%@”,detail);
NSLog(@”weatherInfo字典裡面的內容為–》%@”, weatherDic );
}
在ios中json數據怎麼解析
剛剛下午那會 弄了個 解析 xml demo的小例子,本想著json也挺複雜 弄還是 不弄,但是簡單的看了下 發現挺簡單
考慮了很久,還是寫上來吧,畢竟json用得太多了,而且算是自己的積累吧,畢竟剛開始學習IOS開發方面的知識,就當是鞏固了撒!
還是 先看個效果圖吧,如下!
接下來 看下工程目錄吧,其實並沒有必要,直接建立一個工程就行 ,算了,還是貼上來吧,如下:
工程目錄中有個 Notes.json 文件,該文件就是 要解析的json數據了 ,也截下圖吧,如下:
Ok ,以上準備完畢,就開始編碼了,在此之前故事版的內容 就和我上篇博客文章 IOS 解析xml 故事版 是一樣配置的,這裡就不在啰嗦了 ,首先看下 chonViewController.h文件,代碼如下:
//
// chonViewController.h
// TestJson
//
// Created by choni on 14-5-16.
// Copyright (c) 2014年 choni. All rights reserved.
//
#import UIKit/UIKit.h
@interface chonViewController : UITableViewController
//保存數據列表
@property(nonatomic,strong) NSMutableArray * listData;
@end
與之對應的 chonViewController.m文件 代碼如下:
[objc] view plaincopy在CODE上查看代碼片派生到我的代碼片
//
// chonViewController.m
// TestJson
//
// Created by choni on 14-5-16.
// Copyright (c) 2014年 choni. All rights reserved.
//
#import “chonViewController.h”
@interface chonViewController ()
@end
@implementation chonViewController
– (void)viewDidLoad
{
[super viewDidLoad];
NSString * path = [[NSBundle mainBundle]pathForResource:@”Notes” ofType:@”json” ];
NSData * jsonData = [[NSData alloc] initWithContentsOfFile:path];
NSError * error ;
id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:error];
if (!jsonObj || error) {
NSLog(@”JSON解析失敗”);
}
self.listData = [jsonObj objectForKey:@”Record”];
}
#pragma mark – tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.listData.count;
}
– (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”Cell” forIndexPath:indexPath];
NSMutableDictionary * dict = self.listData[indexPath.row];
cell.textLabel.text = [dict objectForKey:@”Content”];
cell.detailTextLabel.text = [dict objectForKey:@”CDate”];
return cell ;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Ok , 現在就可以編譯運行的程序了 ,但是有個主意的地方 :
1.因為使用 NSJSONSerialization 實現json解碼,要確定你得項目使用IOS 5 SDK 才可以
2. 其他的就沒有什麼了,介紹下NSJSONSerialization的類方法吧
1)NSJSONReadingMutableContaines ,指定解析返回的是可變的數組或字典 ,這個方法還是比較使用的,因為如果json數據需要改,不用管撒
2)NSJSONReadingMutableLeaves ,指定葉節點是可變的字元串
3) NSJSONReadingAllowFragments , 指定頂級節點可以部署數組或字典
iOS開源JSON解析庫MJExtension
iOS中JSON與NSObject互轉有兩種方式:1、iOS自帶類NSJSONSerialization 2、第三方開源庫SBJSON、JSONKit、MJExtension。項目中一直用MJExtension來進行JSON與Model的互轉,非常方便、強大,接下來介紹一下這個輕量、強大的開源庫。
1、什麼是MJExtension?
MJExtension是一套字典和模型之間互相轉換的輕量級開源框架,github地址為: GitHub – CoderMJLee/MJExtension: A fast 。功能如下:
2、MJExtension架構
1)UML類圖
2)類介紹
3、MJExtension JSON轉Model流程圖
4、MJExtension用法舉例
關於用法詳情請見: GitHub – CoderMJLee/MJExtension: A fast 。我這裡只介紹兩種常用的用法,JSON轉Model,JSON轉Model數組
怎麼生成和解析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”]);
原創文章,作者:JFBV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/140647.html