1 , overview
Json
(1) As a lightweight data interchange format, is gradually replacing XML as a universal format for network data
(2) A subset of JavaScript-based
(3) Easy to read, coding handwriting is difficult, the amount of data is small
(4) The JSON format replaces the XML for the network transport to bring great convenience, but there is no clear XML, especially when the JSON data is very long, we will fall into the cumbersome and complex data node lookup
Xml
(1) Extensible Markup Language
(2) Used to mark electronic files with a structured markup language that can be used to tag data, define data types, and be a source language that allows users to define their own markup language
(3) High legibility, coding handwriting difficulty, large data volume
client and server data transfer :
2 , JSON Format Description
N Object
n {}
Structure of key-value pairs for n format {key:value, Key:value,...}
n can be deserialized into nsdictionary in OC
N Array
n []
n format ["Java", "JavaScript", "VB",...]
n can be deserialized into nsarray in OC
N hints
The data format of the n JSON is very similar to the fast wrapping method in OC
The data format of the n JSON also supports nesting
3 , parsing server-side return JSON Data
N Starting with iOS 5, use Nsjsonserialization to parse JSON
n Other common three kinds of JSON parsing third-party libraries:
n Sbjson because the API is easy to use, there may be some applications that remain
N Jsonkit Jsonkit's developers say: Jsonkit performance is better than Apple
N Touchjson
4 , JSON serialization and deserialization of
Deserialization
[Nsjsonserialization jsonobjectwithdata:data options:0 error:null];
For example:
-(void) GetLogon2
{
[Self.view Endediting:yes];
1. Url
NSString *urlstr =
[NSString stringwithformat:@] Http://192.168.40.2/
login.php?username=%@&password=%@ ", Self.userName.text, Self.userPwd.text];
If the URL contains a Chinese character or special characters, such as a space, you need to add a percent escape
Urlstr =
[Urlstr stringbyaddingpercentescapesusingencoding:
Nsutf8stringencoding];
Nsurl *url = [Nsurl urlwithstring:urlstr];
2. Nsurlrequest
/**
Parameters:
timeOutInterval: In the development must specify the timeout time length, the default 60 seconds, usually by the user's network environment, can be set to 10-20 seconds, not too long, nor too short
*/
Nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval: 5.0f];
3. Sending an asynchronous request
[Nsurlconnection sendasynchronousrequest: Request queue:
[[Nsoperationqueue alloc] init] Completionhandler:
^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
if (connectionerror) {
[Self showalertviewwithmsg:@ "network does not give force"];
Return
} else {
// deserializes the received binary data into a data dictionary
nsdictionary *dict =
[Nsjsonserialization jsonobjectwithdata:d ata
Options:nil Error:null];
Loginuser *user = [[Loginuser alloc] initwithdict:dict];
If the user has an avatar, load the avatar
if (user.userimage) {
Dispatch_async (Dispatch_get_main_queue (), ^{
Self.imageView.image =
[User LoadImageWithURL:user.userImage];
});
}
User logon error? No network connection Failed!
if (!user.userid) {
[Self showalertviewwithmsg:@ "username or password is incorrect"];
Return
}
[[Nsoperationqueue Mainqueue]
addoperationwithblock:^{
Self.logonResult.text = @ "Login complete";
}];
}
}];
}
Serialization of
[Nsjsonserialization Datawithjsonobject:array options:0 error:null];
5 , Nsxmlparser
1 , Nsxmlparser Parsing Methods
N Nsxmlparser is the Sax method parsing
n SAX(simpleAPI for XML)
n can only be read, not modified, only sequential access, suitable for parsing large XML, fast parsing speed
n is often applied to XML that processes large amounts of data, enabling data access for heterogeneous systems, enabling cross-platform
n moves through each node from the beginning of the document, locating a specific node
n DOM(Document Object Model)
n can not only read, but also can be modified, and can achieve random access, the disadvantage is that the resolution is slow, suitable for parsing small documents
N General application with small configuration XML for easy operation
n Creates a type description for a document node loaded into memory, presenting a horizontal movement, potentially huge tree structure
n Generating node trees in memory is costly
1. resolution steps:
Memo Property:
@property (nonatomic, strong) Nsmutablearray *datalist;
Back stitching
@property (nonatomic, strong) nsmutablestring *elementstring;
Object for current video information
@property (nonatomic, strong) Video *v;
Also adhere to the agency Agreement: nsxmlparserdelegate
Example code:
-(Ibaction) LoadData
{
1. Url
Nsurl *url =
[Nsurl urlwithstring:@ "http://localhost/videos.php"];
2. Request
Nsurlrequest *request = [nsurlrequest requestwithurl:url cachepolicy:0 timeoutinterval:10.0f];
3. Send Request
[Nsurlconnection sendasynchronousrequest:request queue:
[[Nsoperationqueue alloc] Init]completionhandler:
^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
// First step: Instantiate Nsxmlparser , incoming from the server. XML Data
Nsxmlparser *parser = [[Nsxmlparser alloc] initwithdata:data];
// Step Two: Define the parser agent
Parser.delegate = self;
// Step Three: Parser parsing
[Parser parse];
}];
}
// Fourth step: Through the resolution proxy method to complete XML parsing of data
#pragma Mark 1. Begin
-(void) Parserdidstartdocument: (Nsxmlparser *) parser
{
Preparatory work
1> dataList
if (!self.datalist) {
Self.datalist = [Nsmutablearray array];
} else {
[Self.datalist removeallobjects];
}
2> elementstring
if (!self.elementstring) {
self.elementstring = [nsmutablestring string];
} else {
Empty variable string do not set to nil, use setstring just empty content, next time will not be instantiated
[Self.elementstring setstring:@ ""];
}
}
#pragma Mark 2. All start a node:<element>
-(void) Parser: (Nsxmlparser *) parser didstartelement: (NSString *)elementname NamespaceURI: (NSString *) NamespaceURI qualifiedname: (NSString *) QName attributes: (nsdictionary *)attributedict
{
If it is <video> new object
if ([ElementName isequaltostring:@ "video"]) {
SELF.V = [[Video alloc] init];
Self.v.videoid = attributedict[@ "VideoID"];
}
Empty elementstring before each new node is started
Avoid repeated splicing of the last result
[Self.elementstring setstring:@ ""];
}
#pragma Mark 3. Find content that may be repeated multiple times
-(void) Parser: (Nsxmlparser *) parser foundcharacters: (NSString *) string
{
Stitching strings
[Self.elementstring appendstring:string];
}
#pragma Mark 4. Node End </element>
-(void) Parser: (Nsxmlparser *) parser didendelement: (NSString *) elementname NamespaceURI: (NSString *) NamespaceURI QualifiedName: (NSString *) qName
{
NSLog (@ "End node%@", elementname);
Judging if it is <name> to copy
if ([ElementName isequaltostring:@ "video"]) {
[Self.datalist ADDOBJECT:SELF.V];
} else if (![ ElementName isequaltostring:@ "Videos"]) {
[SELF.V setValue:self.elementString Forkey:elementname];
}
}
#pragma Mark 5. End of document
-(void) Parserdidenddocument: (Nsxmlparser *) parser
{
NSLog (@ "parsing ends%@%@", Self.datalist, [Nsthread CurrentThread]);
Dispatch_async (Dispatch_get_main_queue (), ^{
[Self.tableview Reloaddata];
Turn off refresh of refreshed controls
[Self.refreshcontrol endrefreshing];
});
}
#pragma Mark 6. Error handling
-(void) Parser: (Nsxmlparser *) parser parseerroroccurred: (Nserror *) parseerror
{
NSLog (@ "%@", parseerror.localizeddescription);
}
3 , Nsxmlparser Parsing proxy methods
1. Start parsing XML document
-(void) Parserdidstartdocument:
2. Begins parsing an element, traversing the entire XML, identifying the element node name
-(void) Parser:didStartElement:namespaceURI:qualifiedName:attributes:
3. Text node, get the information stored in the text node data, for big data may be received multiple times! To save memory overhead
-(void) Parser:foundcharacters:
4. End a node, storing information obtained from the Parser:foundcharacters: method
-(void) Parser:didEndElement:namespaceURI:qualifiedName:
Note: During parsing, 2, 3, and 43 methods are repeatedly executed until the traversal is complete
5. Parsing XML document End
-(void) Parserdidenddocument:
6. Parse error
-(void) parser:parseerroroccurred:
JSON & XML for iOS development