IOS development practices in JSON
The data returned by the server to the client is generally in JSON or XML format (except for file downloads). The comparison between JSON and XML is not described here. In general, XML files are huge and the file format is complex. parsing requires a lot of resources and time, and transmission occupies the bandwidth. JSON data format is relatively simple, easy to read and write, the format is compressed, the bandwidth is small, mobile development preferred.
JSON:
1. The JSON format is similar to the dictionary and array in OC.
{"Name": "jack", "age": 10}
{"Names": ["jack", "rose", "jim"]}
Note: The key must use double quotation marks in the standard JSON format.
JSON-OC conversion table:
2. In iOS, there are four common JSON resolution Solutions
Third-party frameworks: JSONKit, SBJson, and TouchJSON (performance from left to right, the worse)
Apple native (built-in): NSJSONSerialization (Best Performance)
Common NSJSONSerialization methods:
2.1 convert JSON to OC object (the process is to convert json to dictionary, and then convert dictionary to object)
+ (Id) JSONObjectWithData :( NSData *) data options :( NSJSONReadingOptions) opt error :( NSError **) error;
Example: The request server returns json data. Json data is encapsulated into an array object.
Json format of the data returned by the server:
-(Void) viewDidLoad {[super viewDidLoad]; NSURL * url = [NSURL URLWithString: @ "http: // localhost: 8080/myService/video"]; NSURLRequest * request = [NSURLRequest requestWithURL: url]; [NSURLConnection failed: request queue: [queue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {if (connectionErro R | data = nil) {[MBProgressHUD showError: @ "the network is busy. Please try again later! "]; Return;} // convert json to data to obtain the dictionary NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; // retrieve a key in the dictionary NSArray * videoArray = dict [@ "videos"]; // dictionary conversion model for (NSDictionary * videoDict in videoArray) {// dictionary-to-model (object) Video * video = [Video videoWithDict: videoDict]; [self. videos addObject: video] ;}}] ;}
2.2 convert OC object to JSON data (convert object to dictionary and then convert dictionary to json)
+ (NSData *) dataWithJSONObject :( id) obj options :( NSJSONWritingOptions) opt error :( NSError **) error;
# Import "ViewController. h "# import" Person. h "@ interface ViewController () @ property (nonatomic, strong) Person * person; @ end @ implementation ViewController-(void) viewDidLoad {[super viewDidLoad]; _ person = [[Person alloc] init]; _ person. name = @ "kobe"; _ person. age = 24; _ person. sex = @ "male"; _ person. phone = @ "1112334444";}-(void) touchesBegan :( NSSet
*) Touches withEvent :( UIEvent *) event {// person to dictionary NSMutableDictionary * dict = [NSMutableDictionary dictionary]; dict [@ "age"] = [NSString stringWithFormat: @ "% d", self. person. age]; dict [@ "name"] = self. person. name; dict [@ "sex"] = self. person. sex; dict [@ "phone"] = self. person. phone; NSData * data = [NSJSONSerialization dataWithJSONObject: dict options: Internal error: nil]; NSString * dataStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; NSLog (@ "% @", dataStr) ;}@ end
Result:
{
"Age": "24 ",
"Sex": "male ",
"Telephone": "1112334444 ",
"Name": "kobe"
}
NSJSONReadingOptions enumeration:
NSJSONReadingMutableContainers: returns a variable container, NSMutableDictionary or NSMutableArray.
NSJSONReadingMutableLeaves: the string value in the returned JSON object is NSMutableString
NSJSONReadingAllowFragments: allows the outermost layer of the JSON string to be either NSArray or NSDictionary, but must be a valid JSON Fragment.
NSJSONWritingPrettyPrinted: formatted output of the generated json data, which is highly readable. If this parameter is not set, the output json string is a whole line.