1 JSON:JavaScript Object Notation
(1)JSON的基本组织形式
(2)JSON的本质就是字符串
{"name":"李四","age":20} {"user":{"name":"李四","age":20}}
[{"name":"张三"},{"name":"李四"}] {"user":[{"name":"张三"},{"name":"李四"}]}
(3)JSON的解析库
(I)iOS原生JSON解析库
(II)第三方库:SBJson、JsonKit、TouchJson
(4)实例分析
// {"name":"李四","age":20} NSString *jsonString = @"{"name":"李四","age":20}"; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 NSDictionary *dic = (NSDictionary *)jsonObj; NSString *name = [dic objectForKey:@"name"]; NSInteger age = [[dic objectForKey:@"age"] integerValue]; NSLog(@"name: %@, age: %d", name, age); } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 }
// {"user":{"name":"李四","age":20}} NSString *jsonString = @"{"user":{"name":"李四","age":20}}"; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 NSDictionary *dic = (NSDictionary *)jsonObj; NSDictionary *userDic = [dic objectForKey:@"user"]; NSString *name = [userDic objectForKey:@"name"]; NSInteger age = [[userDic objectForKey:@"age"] integerValue]; NSLog(@"name: %@, age: %d", name, age); } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 }
// [{"name":"张三"},{"name":"李四"}] NSString *jsonString = @"[{"name":"张三"},{"name":"李四"}]"; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 NSArray *array = (NSArray *)jsonObj; for (NSDictionary *dic in array) { NSString *name = [dic objectForKey:@"name"]; NSLog(@"name: %@", name); } }
// {"user":[{"name":"张三"},{"name":"李四"}]} NSString *jsonString = @"{"user":[{"name":"张三"},{"name":"李四"}]}"; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 NSDictionary *dic = (NSDictionary *)jsonObj; NSArray *array = [dic objectForKey:@"user"]; for (NSDictionary *dic in array) { NSString *name = [dic objectForKey:@"name"]; NSLog(@"name: %@", name); } } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 }
(5)从文件获取数据
NSString *jsonString = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"weatherInfo" ofType:@"json"]; NSFileManager *fm = [NSFileManager defaultManager]; if ([fm fileExistsAtPath:filePath]) { jsonString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; } else { return; } NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil]; if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 }
(6)从网络上获取数据----有三种方式获取Data
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"]; // 第一种方法获取NSData NSData *jsonData = [NSData dataWithContentsOfURL:url]; // 第二种方法获取NSData NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; // 第三种方法获取NSData NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSData *jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
(7)使用第三方库JSONKit
#import “JSONKit.h”
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"]; NSData *jsonData = [NSData dataWithContentsOfURL:url]; JSONDecoder *decoder = [[JSONDecoder alloc] init]; id jsonObj = [decoder objectWithData:jsonData];
if ([jsonObj isKindOfClass:[NSDictionary class]]) { // 字典类型 } if ([jsonObj isKindOfClass:[NSArray class]]) { // 数组类型 }
(8) 使用第三方库TouchJson
#import "CJSONDeserializer.h"
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"]; NSData *jsonData = [NSData dataWithContentsOfURL:url]; CJSONDeserializer *des = [CJSONDeserializer deserializer]; id jsonObj = [des deserialize: des, error: nil];
(9) 使用第三方库SBJSON
#import "SBJSONParser.h"
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/data/cityinfo/101010100.html"]; NSData *jsonData = [NSData dataWithContentsOfURL:url]; SBJSONParser *parser = [[SBJSONParser alloc] init]; id jsonObj = [parser objectWithData: jsonData];
(10) json数据解析总结
(I)优先使用iOS自带的解析器
(a)自带解析器(类方法) 类名:NSJSONSerialization 方法名:JSONObjectWithData:options:error:
(b)JSONKit(实例方法) 类名:JSONDecoder 方法名:objectWithData:
(c)TouchJson(实例方法)类名:CJSONDeserializer 方法名:deserialize:error:
(d)SBJSON(实例方法) 类名:SBJSONParser 方法名:objectWithData:
(II)第三方库使用步骤
(a)下载并拷贝到工程路径下
(b)以create group方式导入工程
(c)如果工程使用ARC,则针对导入的文件添加-fno-objc-arc命令
(III)json数据解析步骤:
(a)从数据源获取json数据
(b)将json数据转为NSDictionary或NSArray
(c)解析NSDictionary或NSArray
2 XML:Extensible Markup Language 可扩展标记语言
(1)XML实例
<info>James</info> <info name="James"></info> <info><name>James</name></info> <info><name>James</name><name>Jam</name></info>
(2)使用NSXMLParser解析XML文件
需要实现5个代理:
NSXMLParserDelegate
// 准备解析 - (void)parserDidStartDocument:(NSXMLParser *)parser; // 准备解析当前节点 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict; // 准备首位节点间内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string; // 解析完当前节点 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName; // 解析结束 - (void)parserDidEndDocument:(NSXMLParser *)parser;
(3)实例分析
{
NSString *xmlStr = @"<info>James</info>"; NSData *xmlData = [xmlStr dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *xmlParse = [[NSXMLParser alloc] initWithData:xmlData]; xmlParse.delegate = self; [xmlParse parse];
}
#pragma mark NSXMLParserDelegate // 准备解析 - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__); } // 准备解析当前节点 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{ NSLog(@"%s", __FUNCTION__); } // 准备首位节点间内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"%s", __FUNCTION__); NSLog(@"%@", string); } // 解析完当前节点 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{ NSLog(@"%s", __FUNCTION__); } // 解析结束 - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__); } //打印结果 2017-03-02 16:57:14.478 UsingWebView[93924:11407847] -[ViewController parserDidStartDocument:] 2017-03-02 16:57:14.480 UsingWebView[93924:11407847] -[ViewController parser:didStartElement:namespaceURI:qualifiedName:attributes:] 2017-03-02 16:57:14.481 UsingWebView[93924:11407847] -[ViewController parser:foundCharacters:] 2017-03-02 16:57:14.481 UsingWebView[93924:11407847] James 2017-03-02 16:57:14.482 UsingWebView[93924:11407847] -[ViewController parser:didEndElement:namespaceURI:qualifiedName:] 2017-03-02 16:57:14.482 UsingWebView[93924:11407847] -[ViewController parserDidEndDocument:]
{
NSString *xmlStr = @"<info name="James" age="20"></info>";
NSData *xmlData = [xmlStr dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *xmlParse = [[NSXMLParser alloc] initWithData:xmlData]; xmlParse.delegate = self; [xmlParse parse]; } #pragma mark NSXMLParserDelegate // 准备解析 - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__);
_mutableDic = [NSMutableDictionary dictionary]; } // 准备解析当前节点 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{ NSLog(@"%s", __FUNCTION__); for (NSString *key in [attributeDict allKeys]) {
[_mutableDic setObject: attributeDict[key] forKey: key];
} } // 准备首位节点间内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"%s", __FUNCTION__); NSLog(@"%@", string); } // 解析完当前节点 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{ NSLog(@"%s", __FUNCTION__); } // 解析结束 - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__);
NSLog(@"%s", _mutableDic);
}
//打印结果 2017-03-02 16:58:03.503 UsingWebView[93954:11410104] -[ViewController parserDidStartDocument:] 2017-03-02 16:58:03.505 UsingWebView[93954:11410104] -[ViewController parser:didStartElement:namespaceURI:qualifiedName:attributes:]2017-03-02 16:58:03.505 UsingWebView[93954:11410104] -[ViewController parser:didEndElement:namespaceURI:qualifiedName:] 2017-03-02 16:58:03.506 UsingWebView[93954:11410104] -[ViewController parserDidEndDocument:]
2017-03-02 16:58:03.507 UsingWebView[93954:11410104] {
age = 20;
name = James;
}
{ NSString *xmlStr = @"<info><name>James</name><name>Jam</name></info>"; NSData *xmlData = [xmlStr dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *xmlParse = [[NSXMLParser alloc] initWithData:xmlData]; xmlParse.delegate = self; [xmlParse parse]; } #pragma mark NSXMLParserDelegate // 准备解析 - (void)parserDidStartDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__); _mutableArray = [NSMutableArray array]; } // 准备解析当前节点 - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{ NSLog(@"%s", __FUNCTION__); } // 准备首位节点间内容 - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ NSLog(@"%s", __FUNCTION__); NSLog(@"%@", string); [_mutableArray addObject:string]; } // 解析完当前节点 - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{ NSLog(@"%s", __FUNCTION__); } // 解析结束 - (void)parserDidEndDocument:(NSXMLParser *)parser { NSLog(@"%s", __FUNCTION__); NSLog(@"%@", _mutableArray); } // 打印结果 2017-03-02 17:02:09.760 UsingWebView[94039:11419779] -[ViewController parserDidStartDocument:] 2017-03-02 17:02:09.760 UsingWebView[94039:11419779] -[ViewController parser:didStartElement:namespaceURI:qualifiedName:attributes:] 2017-03-02 17:02:09.761 UsingWebView[94039:11419779] -[ViewController parser:didStartElement:namespaceURI:qualifiedName:attributes:] 2017-03-02 17:02:09.761 UsingWebView[94039:11419779] -[ViewController parser:foundCharacters:] 2017-03-02 17:02:09.761 UsingWebView[94039:11419779] James 2017-03-02 17:02:09.762 UsingWebView[94039:11419779] -[ViewController parser:didEndElement:namespaceURI:qualifiedName:] 2017-03-02 17:02:09.762 UsingWebView[94039:11419779] -[ViewController parser:didStartElement:namespaceURI:qualifiedName:attributes:] 2017-03-02 17:02:09.762 UsingWebView[94039:11419779] -[ViewController parser:foundCharacters:] 2017-03-02 17:02:09.762 UsingWebView[94039:11419779] Jam 2017-03-02 17:02:09.762 UsingWebView[94039:11419779] -[ViewController parser:didEndElement:namespaceURI:qualifiedName:] 2017-03-02 17:02:09.763 UsingWebView[94039:11419779] -[ViewController parser:didEndElement:namespaceURI:qualifiedName:] 2017-03-02 17:02:09.763 UsingWebView[94039:11419779] -[ViewController parserDidEndDocument:] 2017-03-02 17:02:09.835 UsingWebView[94039:11419779] ( James, Jam )
注意:可以在parserDidStartDocument:方法中定义一个数组或字典来接受数据。