本文目錄一覽:
iOS Swift JSONEncoder和JSONDecoder解析數據
本人親測有效!絕對可靠!更多交流可以家魏鑫:lixiaowu1129,一起探討iOS相關技術!
一個對象如果需要被編碼/解碼的話,該對象所屬的類需要遵循 Decodable Encodable 協議。
以 Player 這類為例,Player遵循了 Decodable 和 Encodable
初始化一個Player對象,並對其進行編碼和解碼,看看編碼和解碼之後的數據
一個對象被jsonEncode後,對象將被轉成 Data 類型的數據。
再將對象的 Data 數據通過jsonDecode,可以還原原來的對象。
通過對對象的json編碼和解碼,有助於我們理解數據在計算機中的存儲。Data 其本質就是二進制流。
這是一個字符串
如何將其解析成player對象?
這種情況多用於客戶端向服務端發送HTTP請求之後,解析返回數據,如果後台返回的是標準的JSON字符串的話直接這樣解析就可以了。
Serialization 是序列化的意思,JSONSerialization 顧名思義是對JSON進行序列化。
JSONSerialization 是對 JSON 字符串進行序列化和反序列化的工具類。用這個類可以將JSON轉成對象,也可以將對象轉成JSON。
打印結果為:
這是一個標準的,帶轉義的JSON字符串。也就是說我們將字典轉成了JSON字符串。
打印結果為:
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數據怎麼解析
剛剛下午那會 弄了個 解析 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格式數據
導語: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”]);
原創文章,作者:EOOJY,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/316544.html