JSON is a lightweight data interchange format that is ideal for data interaction between networks. The format of JSON is similar to the dictionary and array in OC.
Key-value formatted:
" Age ":
In array format:
["Tom""Jack"]
In iOS development, if you want to use JSON, you need to parse the JSON. In iOS, the parsing scheme of JSON mainly has the following four solutions:
1, Nsjsonserialization
2, Jsonkit
3, Sbjson
4, Touchjson
The top four scenarios are getting worse from top to bottom, with the first solution being Apple's own solution, the best performance, and recommend this option. The following three are third-party frameworks that can be learned on GitHub. Let's focus on nsjsonserialization.
1. JSON to OC Object
JSON-to-OC object has two classes of methods
+ (ID) Jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error; + (ID) Jsonobjectwithstream: (Nsinputstream *) stream options: (nsjsonreadingoptions) opt error: (Nserror *) Error
The first class method is to create OC objects from JSON data of the NSData type, and the second is to create OC objects from the JSON data stream of the Nsinputstream type, with the following comments on the function source of the option parameter:
If the parser should allow top-level objects that is not a nsarray or nsdictionary. Setting the nsjsonreadingmutablecontainers option would make the parser generate mutable nsarrays and nsdictionaries. Setting the nsjsonreadingmutableleaves option would make the parser generate mutable nsstring objects.
Nsjsonreadingmutablecontainers: Returns a variable container, such as Nsmutablearray, nsmutabledictionary
Nsjsonreadingmutableleaves: Return nsmutablestring Object
Nsjsonreadingallowfragments: Allows the outermost layer of the JSON string to be neither an array nor a dictionary, but must be a valid JSON Fragment, such as @ "123". Here's a look at the test code:
- (void) SendDemo0 {//Verify that the user name is emptyNSString *username =Self.userNameField.text; if(username.length<=0) {Mbprogresshud*hud =[Mbprogresshud ShowHUDAddedTo:self.view Animated:yes]; [HUD hide:yes Afterdelay:1]; [HUD Setlabeltext:@"user name cannot be empty"]; [HUD Setmode:mbprogresshudmodecustomview]; return; } //Verify that the password is emptyNSString *pwd =Self.userPwdField.text; if(pwd.length<=0) {Mbprogresshud*hud =[Mbprogresshud showhudaddedto:[uiapplication sharedapplication].windows.lastobject Animated:YES]; [HUD hide:yes Afterdelay:1]; [HUD Setlabeltext:@"The password cannot be empty"]; [HUD Setmode:mbprogresshudmodecustomview]; return; } //Show a Load boxMbprogresshud *hud =[Mbprogresshud showhudaddedto:[uiapplication sharedapplication].windows.lastobject Animated:YES]; Hud.labeltext=@"is loading"; Hud.dimbackground=YES; Hud.removefromsuperviewonhide=YES; //send an HTTP request to log inNSString *str = [NSString stringWithFormat:@"http://localhost:8080/mjserver/login?username=%@&pwd=%@", UserName, PWD]; Nsurl*url =[Nsurl Urlwithstring:str]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) { //processing of the returned data, such as JSON parsingNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; //Display the prompt informationMbprogresshud *messagehud =[Mbprogresshud ShowHUDAddedTo:self.view Animated:yes]; Messagehud.removefromsuperviewonhide=YES; Messagehud.mode=Mbprogresshudmodetext; [Messagehud Show:yes]; NSString*error = [Dict objectforkey:@"Error"]; if(Error) {Messagehud.labeltext=error; }Else{Messagehud.labeltext= [Dict Objectforkey:@"Success"]; } [Messagehud Hide:yes afterdelay:1]; [HUD Hide:yes]; }]; }
Mbprogresshud is a third-party framework to display a load box or message prompt, Nsurlconnection is used to send a network request to get JSON data, these two classes are now used, and later specifically said.
2. OC object to JSON
OC object to JSON has a static method:
+ (NSData *) Datawithjsonobject: (ID) obj options: (nsjsonwritingoptions) opt error: (NSERROR *) error;
The parameter obj should be a valid JSON format, and if an invalid JSON is provided, this method throws an exception and detects if the method is valid:
+ (BOOL) Isvalidjsonobject: (id) obj;
Returns YES if it is valid, otherwise returns no, the valid object must have the following properties:
Object is An Nsarray or nsdictionary -All objects is NSString, NSNumber, Nsarray, nsdictionary, or NSNull -All dictionary keys is nsstring S -nsnumbers is not NaN or infinity
The outermost object is Nsarray or Nsdictionary, where the object is NSString, NSNumber, Nsarray, nsdictionary, or nsnull, and all dictionary keys must be of type NSString, NSNumber cannot be Nan or infinity.
The OPT parameter has only one option: nsjsonwritingprettyprinted,
Setting the nsjsonwritingprettyprinted option would generate JSON with whitespace designed to make the output more readable .
After setting this parameter, the JSON data can be formatted to make the output more readable. The test code is as follows: (followed by the test code above)
NSData *data1 = [nsjsonserialization datawithjsonobject:dict options:nsjsonwritingprettyprinted Error:nil]; *STR = [[NSString alloc] initwithdata:data1 encoding:nsutf8stringencoding]; NSLog (@ "str:%@", str);
The output results are as follows:
---ten:48.308 httpdemo[56455:607 ] str:{ "error"" user name does not exist " }
Finally attach the test Demo:demo
About the use of JSON in web development