JSON and XML one, JSON1. What is JSON
- JSON is a lightweight data format that is typically used for data interaction
- Data returned by the server to the client, usually in JSON format or XML format (except for file downloads)
The format of 2.JSON is much like the dictionary and array in OC
{"name" : "jack", "age" : 10}{"names" : ["jack", "rose", "jim"]}
- Note points in the standard JSON format:
key必须用双引号
- To dig out specific data from JSON, you have to parse the JSON
JSON |
OC |
Curly braces {} |
Nsdictionary |
Brackets [] |
Nsarray |
Double quote "" |
NSString |
Digital |
NSNumber |
True/false |
NSNumber |
Null |
NSNull |
- JSON conversion to OC data type
3. In iOS, the common parsing scheme for JSON has 4 ① third-party frameworks: Jsonkit, Sbjson, Touchjson (performance from left to right, Less) ② Apple native (comes with): Nsjsonserialization (Best performance) nsjsonserialization common methods JSON data, OC Object
/* 第一个参数:需要解析的JSON数据 第二个参数:解析JSON的可选配置参数 NSJSONReadingMutableContainers 解析出来的字典和数组是可变的 NSJSONReadingMutableLeaves 解析出来的对象中得字符串是可变的,iOS7以后有问题 NSJSONReadingAllowFragments 解析出来的JSON数据既不是字典也不是数组,那么就必须使用这个 */+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
IOS5 self-contained parsing class Nsjsonserialization parse data from response into a dictionary
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
OC Object--JSON data
/* 第一个参数:需要转换为JSON数据的OC对象 第二个参数:毫无意义 NSJSONWritingPrettyPrinted:对转换之后的JSON进行排版*/+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
4. View the complex JSON data ① online conversion to view formatting
Http://tool.oschina.net/codeformat/json
② directly writes the converted data to a local
NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];[dict writeToFile:@"路径" atomically:YES];
5.JSON Turn dictionary, dictionary re-model
- Mantle
- All models must inherit from Mtmodel.
- Jsonmodel
- All models must inherit from Jsonmodel.
- Mjextension
- There is no need to force inheritance of any other class
Issues to be considered in the design framework
- Invasive
- A big intrusion means it's hard to get out of this frame.
- Ease of Use
- Compare small amounts of code to achieve n versatility
- Scalability
- It's easy to add a new framework to this framework
Second, XML1. What is XML
- Full name is extensible Markup Language, translated "Extensible Markup Language"
- Like JSON, it's also a common format for interacting data.
- Generally also called XML document (XML documents)
2.XML Example
<videos> <video name="小黄人 第01部" length="30" /> <video name="小黄人 第02部" length="19" /> <video name="小黄人 第03部" length="33" /></videos>
3. A common XML document typically consists of the following sections
- Document Declaration
- Elements (Element)
- Properties (Attribute)
4. At the front of the XML document, you must write a document declaration that declares the type of the XML document
5. An element includes a start tag and an end tag
- Elements that have content:
<video>小黄人</video>
- Elements with no content:
<video></video>
- Shorthand for elements without content:
<video/>
- An element can nest several child elements (no cross-nesting)
<videos> <video> <name>小黄人 第01部</name> <length>30</length> </video></videos>
- Canonical XML documents have a maximum of 1 root elements, and other elements are descendants of the root element
All spaces and line breaks in 6.XML will be treated as specific content
- The contents of the following two elements are not the same
- 1th One
<video>小黄人</video>
- 2nd One
<video> 小黄人</video>
7. An element can have multiple properties
<video name="小黄人 第01部" length="30" />
- The video element has a name and length two properties
- Attribute values must be enclosed in double quotation marks "" or single quotes "
In fact, the information represented by a property can also be represented by a child element, such as
<video> <name>小黄人 第01部</name> <length>30</length></video>
Third, XML parsing
- To extract useful information from XML, you have to learn to parse the XML
- Extract the contents of the name element
<name>小黄人 第01部</name>
Extract the value of the name and length property in the video element
<video name="小黄人 第01部" length="30" />
There are 2 ways to parse 1.XML
- DOM: Loading an entire XML document into memory at once, which is more suitable for parsing small files
- SAX: Starting from the root element, in order to parse an element down, it is more suitable for parsing large files
XML parsing in iOS in iOS, there are many ways to parse XML 1. Apple native
- Nsxmlparser:sax method analysis, easy to use
2. Third-party frameworks
- LIBXML2: pure C language, which is included by default in the iOS SDK while supporting DOM and sax parsing
- Gdataxml:dom method Analysis, developed by Google, based on LIBXML2
Suggestions for choosing XML parsing methods
- Large files: Nsxmlparser, LIBXML2
- Small files: Gdataxml, Nsxmlparser, LIBXML2
2.NSXMLParser
- Nsxmlparser take is the sax parsing, characterized by event-driven, the following situation will notify the agent
- When scanning to the beginning and end of documents (document)
- When scanning to the start and end of elements (element)
Use step ①. Start parsing
// 传入XML数据,创建解析器NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];// 设置代理,监听解析过程parser.delegate = self;// 开始解析(parse方法是阻塞式的)[parser parse];
②.nsxmlparserdelegate
Called when scanning to the beginning of a document (parsing is started)-(void) parserdidstartdocument: (Nsxmlparser *) Parser// Called when scanning to the end of the document (parsing completed)-(void) parserdidenddocument: (Nsxmlparser *) Parser//is called when scanning to the beginning of an element (Attributedict holds the attributes of the Element)-(void) Parser: (Nsxmlparser *) Parser didstartelement: (nsstring *) elementname NamespaceURI: ( nsstring *) NamespaceURI qualifiedname: (NSString *) qName Attributes: (nsdictionary *) Attributedict//when scanning to the end of an element called-( void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (nsstring *) NamespaceURI qualifiedname: (nsstring *) qName
3.gdataxml①gdataxml Configuration
- Gdataxml based on the LIBXML2 library, you have to do the following configuration
Import LIBXML2 Library
Set the LIBXML2 header file search path (in order to find all header files for the LIBXML2 library)
- Add/USR/INCLUDE/LIBXML2 to head Search path
Set link parameters (Auto link libxml2 library)
- Add-LXML2 to other Linker flags
Because the Gdataxml is non-arc, you have to set the compilation parameters
②gdataxml using classes commonly used in Gdataxml
- Gdataxmldocument: Representing the entire XML document
Gdataxmlelement
- Represents each element in a document
- Use the Attributeforname: method to get the property value
1. Create a URLNsurl *url = [Nsurl URLWithString:@ "Http://120.25.226.186:32812/video?type=XML"];2. Create a request based on a URLNsurlrequest *request = [Nsurlrequest Requestwithurl:url];3. Send a request using nsurlconnection [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response,NSData *data,Nserror *connectionerror) {1. Load all XML into memory gdataxmldocument *doc = [[Gdataxmldocument alloc] initwithdata:data options:kniloptions Error:NIL];2. Get the root element gdataxmlelement *rootelement = doc. rootelement;3. Get all child elements from the root elementNsarray *elements = [rootelement elementsforname:@ "video"];4. Convert a property in a child element to a modelfor (Gdataxmlelement *elein elements) {Xmgvideo *video = [[Xmgvideo alloc] init]; Video.image = [ele attributeforname:@ "image"].stringvalue; Video.url = [ele Attributeforname:@ "url"].stringvalue; Video.name = [ele attributeforname:@" name "].length = @ ([ele attributeforname:@ "Length"].stringvalue.integervalue); [self.videos Addobject:video];} [self.tableview Reloaddata];}];
Iv. JSON and XML comparisons
- The same data can be expressed either in JSON or in XML.
- In contrast, JSON is smaller than XML, so the data format that the server returns to the mobile side is mostly JSON
V. Use Apple's official API to play the video
// 创建视频播放器MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:urlStr]];// 显示视频[self presentViewController:vc animated:YES completion:nil];
IOS-JSON and XML parsing