IOS JSON data parsing and iosjson data parsing
JSON is a common data format, which is clearer than the XML layer. Here we introduce two methods for parsing JSON: NSJSONSerialization and JSONKit.
NSJSONSerialization was launched after iOS 5 and is a relatively easy-to-use JSON parsing package.
The JSON data format consists of the corresponding '[', ']' and '{', '}'. The former indicates an array, and the latter indicates a dictionary.
NSJSONSerialization parsing process:
1. Get the file path
2. Get File Content
3. Resolution
Simple Example:
1-(IBAction) parserJSON :( id) sender {2 3 // obtain the file path 4 5 NSString * jsonPath = [[NSBundle mainBundle] pathForResource: @ "Student" ofType: @ "json"]; 6 NSError * error = nil; 7 NSData * jsonData = [NSData paths: jsonPath]; 8 NSMutableArray * array = [NSJSONSerialization JSONObjectWithData: jsonData options: response error: & error]; 9 if (error = nil) {10 NSLog (@ "% @", array); 11} else {12 NSLog (@ "% @", error); 13} 14 15 // data encapsulation 16 17 NSMutableArray * arr = [NSMutableArray array]; 18 19 for (NSDictionary * dic in array) {20 Student * stu = [[Student alloc] initWithDictionary: dic]; 21 [arr addObject: stu]; 22} 23 24 for (Student * stu in arr) {25 NSLog (@ "% @", stu); 26} 27}
JSONKit parsing: (CODE)
1-(IBAction) parserJSONWithJESONKIT :( id) sender {2 3 // get File Path 4 5 NSString * jsonPath = [[NSBundle mainBundle] pathForResource: @ "Student" ofType: @ "json"]; 6 NSError * error = nil; 7 NSString * JSONStr = [[NSString alloc] initWithContentsOfFile: jsonPath encoding: NSUTF8StringEncoding error: & error]; 8 NSLog (@ "% @", JSONStr); 9 // Let jesonKIT parse JSON data 10 NSMutableArray * array = [JSONStr objectFromJSONString]; 11 NSLog (@ "% ld ", array. count); 12 // data encapsulation 13 NSMutableArray * arr = [NSMutableArray array]; 14 15 for (NSDictionary * dic in array) {16 Student * stu = [[Student alloc] initWithDictionary: dic]; 17 [arr addObject: stu]; 18} 19 20 for (Student * stu in arr) {21 NSLog (@ "% @", stu); 22} 23}