Using NSJSONSerialization in iOS to parse JSON data and google Geographic Information Processing

Source: Internet
Author: User

In iOS development, when it comes to obtaining data processing in json format from the network, we will think of many open-source third-party packages, such as SBJSON. In iOS5, the processing capability for json format data is also added, and the added class is NSJSONSerialization. NSJSONSerialization can be used to analyze json data in various complex formats. The class method used is + (id) JSONObjectWithData :( NSData *) data options :( NSJSONReadingOptions) opt error :( NSError **) error. Set different options based on the structure of different data. There are three options: NSJSONReadingMutableContainers, NSJSONReadingMutableLeaves, and NSJSONReadingAllowFragments. The apple documentation describes these three methods. 1. Keys that arrays and dictionaries are created as mutable objects.2, keys that leaf strings in the JSON object graph are created as instances of NSMutableString.3. Keys that the parser shocould allow top-level objects that are not an instance of NSArray or NSDictionary. available in iOS 5.0 and later. I would like to ww Ipv2cto.com is tested. This is google's geographic information api, which obtains information such as longitude and latitude Based on the location. The json format of this url is as follows: [javascript] {"results": [{"address_components": [{"long_name": "Nanjing", "short_name ": "Nanjing", "types": ["locality", "political"] },{ "long_name": "Jiangsu Province", "short_name": "Jiangsu Province", "types ": ["administrative_area_level_1", "political"] },{ "long_name": "China", "short_name": "CN", "types": ["country ", "political"]}], "formatted_address": "Nanjing City, Jiangsu Province, China", "geometry ":{ "Bounds": {"northeast": {"lat": 32.61436330, "lng": 119.23624250}, "southwest": {"lat": 31.22809770, "lng ": 118.36337310 }}, "location": {"lat": 32.0602550, "lng": 118.7968770}, "location_type": "APPROXIMATE", "viewport": {"northeast ": {"lat": 32.39401350, "lng": 119.0501690}, "southwest": {"lat": 31.80452470, "lng": 118.42533230 }}, "types ": ["locality", "politic Al "]}]," status ":" OK "} This is a complex json format. json contains arrays and arrays contain several levels of json data. First, transcode the URL to UTF8, create an NSMutableURLRequest based on it, and then use the sendAsynchronousRequest method of NSURLConnection to put the response data into the block for analysis. The analysis method is NSJSONSerialization class + (id) JSONObjectWithData :( NSData *) data options :( NSJSONReadingOptions) opt error :( NSError **) error. The analysis procedure is as follows: Step 1: Obtain the dictionary NSDictionary * resultsDic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: & error] based on the json data structure. Step 2, according to the composition in the dictionary, the object corresponding to the key @ "results" is an array. NSArray * resultsArr = [resultsDic objectForKey: @ "results"]; Step 3: Use the for loop to traverse this array for (NSDictionary * resultDetailDic in resultsArr) {NSDictionary * locationDic = [[resultDetailDic objectForKey: @ "geometry"] objectForKey: @ "location"]; NSString * lat = [locationDic objectForKey: @ "lat"]; NSString * lng = [locationDic objectForKey: @ "lng"]; dispatch_async (dispatch_get_main_queue (), ^ {NSLog (@ "locationDic. lat is ---> % @ \ N ", lat); NSLog (@" locationDic. lng is ---> % @ \ n ", lng) ;}); // dispatch async main} Step 4. Based on the for loop traversal results, each element is a dictionary. NSDictionary * locationDic = [[resultDetailDic objectForKey: @ "geometry"] objectForKey: @ "location"]; Step 5: Based on the dictionary information, the object corresponding to each key is a string, which is the final data we need. If you think this data analysis is too closely related to the data structure, you can make some isKindOfClass judgments. The Code is as follows: [cpp]-(void) parseJson :( NSString *) addr {// The URL of JSON service NSString * _ urlString = @ "http://maps.googleapis.com/maps/api/geocode/json? Address = nanjing & sensor = true "; NSString * _ dataString = [[NSString alloc] initWithData: [_ urlString dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES] encoding: enabled] // _ dataString = [NSString stringwithuf8string: [_ urlString UTF8String]; NSURL * _ url = [NSURL URLWithString: _ dataString]; NSMutableURLRequest * _ request = [Your requestWithURL: _ url]; [_ request SetValue: @ "accept" accept: @ "application/json"]; [NSURLConnection sendAsynchronousRequest: _ request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * error) {// block define statment failed * httpResponse = (NSHTTPURLResponse *) response; int responseStatusCode = [httpResponse statusCode]; NSLog (@ "response status code is % d ", re Eclipsestatuscode); NSError * _ errorJson = nil; NSDictionary * resultsDic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: & error]; if (_ errorJson! = Nil) {NSLog (@ "Error % @", [_ errorJson localizedDescription]);} else {NSString * resultStatus = [resultsDic objectForKey: @ "status"]; if ([resultStatus isEqualString: @ "OK"]) {NSArray * resultsArr = [resultsDic objectForKey: @ "results"]; // Do something with returned array for (NSDictionary * resultDetailDic in resultsArr) {NSDictionary * locationDic = [[resultDetailDic objectForKey: @ "geometry"] objec TForKey: @ "location"]; NSString * lat = [locationDic objectForKey: @ "lat"]; NSString * lng = [locationDic objectForKey: @ "lng"]; dispatch_async (dispatch_get_main_queue (), ^ {NSLog (@ "locationDic. lat is ---> % @ \ n ", lat); NSLog (@" locationDic. lng is ---> % @ \ n ", lng) ;}); // dispatch async main }}}];} through this code, we can implement asynchronous reading, json format data analysis. These operations do not need to call any third-party code, but only use the features provided by apple. This facilitates maintenance and upgrade.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.