IOS ----- JSON parsing, iosjson
JSON Parsing
JSON is a widely used data exchange format. JSON also has cross-platform and cross-language advantages, and uses JSON as the data exchange format for less data transmission.
Basic JSON knowledge
The full name of JSON is JavaScript Object Notation, which is the JavaScript Object symbol. It is a lightweight data exchange format. the JSON data format is suitable for reading/writing by users and for parsing and generating computers themselves.
JSON mainly has the following two data structures: |
The data structure composed of key-value pairs has different implementations in different languages. For example, JavaScript is an object, Objective-C is an NSDictionary object, and C is a struct object. In other languages, it can be implemented by record, dictionary, and hash table. |
Ordered Sets can be implemented in different languages, such as NSArray, vector, array, and sequence. |
There are two main types of JSON syntax in JavaScript: one is used to create an object and the other is used to create an array. |
Create an object using JSON syntax
When an object is created in JSON, it always ends with {start, end with}. Each attribute name and attribute value of the object are separated by a colon (:), and multiple attribute definitions are separated by commas. the syntax format is as follows:
1 object = 2 3 { 4 5 propertyName1 : propertyValue1, 6 7 propertyName2 : propertyValue2, 8 9 …10 11 }
Create an Array Using JSON syntax
Creating an Array Using JSON syntax always starts with square brackets ([), and then puts the array elements in sequence. Elements and elements are separated by commas, the last array element does not need to be followed by a comma, but is enclosed in square brackets (]). the syntax format for creating Arrays Using JSON is as follows:
Arr = [value1, value2,…];
The JSON tool of Objective-C also provides two similar functions. |
Convert an Objective-C object to a JSON string |
Returns a string in JSON format to an Objective-C object. |
Use NSJSONSerialization to process JSON data
The NSJSONSerialization class provides the following class methods to support JSON parsing or generation.
NSJSONSerialization can only convert objects that meet the following conditions into JSON data
Parse JSON data using SBJson
SBJson can also perform bidirectional conversion. The main tool classes are SBJsonParser and SBJsonWriter,
SBJsonParser is responsible for converting JSON data in the form of NSData or NSString to an Objective-C object;
SBJsonWriter converts Objective-C objects to JSON data in the form of NSData or NSString.
Use JSONKit to parse JSON data
1 ViewController. m 2 3 # import "ViewController. h "4 5 # import" SBJson. h "6 7 # import" JSONKit. h "8 9 @ implementation ViewController 10 11 NSArray * books; 12 13 NSArray * parseResult; 14 15 NSString * tableTitle; 16 17-(void) viewDidLoad 18 19 {20 21 [super viewDidLoad]; 22 23 // define an Objective-C NSArray data, in this example, three methods are used to convert the object to JSON data 24 25 books = [NSArray arrayWithObjects: 26 27 [NSDictionary dictionaryWithObjectsAndKeys @ "", @ "title ", 28 29 @ "Edited by Cao Xueqin", @ "author", 30 31 @ "the epitome of the great history of the Qing Dynasty", @ "remark", nil], 32 33 [NSDictionary dictionaryWithObjectsAndKeys @ "Romance of the Three Kingdoms", @ "title", 34 35 @ "Edited by Luo Guanzhong", @ "author ", 36 37 @ "the world points for a long time and points for a long time", @ "remark", nil], 38 39 [NSDictionary dictionaryWithObjectsAndKeys @ "Journey to the West", @ "title ", 40 41 @ "Edited by Wu chengen", @ "author", 42 43 @ "go to the West to get the scriptures", @ "remark", nil], 44 45 [NSDictionary dictionaryWithObjectsAndKeys @ "Water Margin ", @ "title", 46 47 @ "Edited by Shi Nai", @ "author", 48 49 @ "", @ "remark", nil] 50 51, nil]; 52 53 self. tableView. dataSource = self; 54 55} 56 57-(IBAction) JSONSerializationParser :( id) sender 58 59 {60 61 // obtain the path of the JSON file 62 63 NSString * jsonPath = [[NSBundle mainBundle] pathForResource: @ "books" 64 65 ofType @ "json"]; 66 67 // read data of the jsonPath file 68 69 NSData * data = [NSData dataWithContentsOfFile: jsonPath]; 70 71 // parse JSON data, returns the Objective-C object 72 73 parseResult = [NSJSONSerialization JSONObjectWithData: data 74 75 options: 0 error: nil]; 76 77 tableTitle = @ "parsed using JSONSerializationParse "; 78 79 // Let tableView reload data 80 81 [self. tableView reloadData]; 82 83} 84 85-(IBAction) SBParser :( id) sender 86 87 {88 89 // obtain the path of the JSON file 90 91 NSString * jsonPath = [[NSBundle mainBundle] pathForResource: @ "books" 92 93 ofType: @ "json"]; 94 95 // read the data of the jsonPath file 96 97 NSData * data = [NSData dataWithContentsOfFile: jsonPath]; 98 99 // create SBJsonParser object 100 101 SBJsonParser * jsonParser = [[SBJsonParser alloc] init]; 102 103 parserResult = [jsonParser objectWithData: data]; 104 105 tableTitle = @ "use SBJson resolution"; 106 107 108 // Let tableView reload data 109 [self. tableView reloadData]; 110 111} 112 113-(IBAction) JSONKitParse :( id) sender114 115 {116 117 // obtain the path of the JSON file 118 NSString * jsonPath = [[NSBundle mainBundle] pathForResource: @ "books" 119 120 ofType: @ "json"]; 122 123 // read data of the jsonPath file 124 125 NSData * data = [NSData dataWithContentsOfFile: jsonPath]; 126 127 // call the objectFromJSONData method extended by JSONKit to parse JSON data 128 129 parseResult = [data objectFromJSONData]; 130 131 tableTitle = @ "use JSONKit to parse "; 132 133 // Let tableView reload data 134 135 [self. tableView reloadData]; 136 137} 138 139-(IBAction) JSONSerializtionGenerate :( id) sender140 141 {142 143 // call the NSJSONSerialization class method to convert the Objective-C object to JSON data 144 145 NSData * data = [NSJSONSerialization dataWithJSONObject: books146 147 options: 0 error: nil]; 148 149 // convert the JSON data in NSData format to the string 150 151 NSString * json = [[NSString alloc] initWithData: data152 153 encoding: NSUTF8StringEncoding]; 154 155 NSLog (@ "NSJSONSerialization conversion string: % @", json); 156 157} 158 159-(IBAction) SBGenerate :( id) sender160 161 {162 163 // create SBJsonWriter object 164 165 SBJsonWriter * jsonWriter = [[SBJsonWriter alloc] init]; 166 167 // call the SBJsonWriter object method to convert the Objective-C object to the JSON string 168 169 NSLog (@ "SBJson conversion to get the string: % @", [jsonWriter stringWithObject: books]); 170 171} 172 173-(IBAction) JSONKitGenerate :( id) sender174 175 {176 177 // call JSONKit to extend the JSONString method of the NSArray object to convert the Objective-C object to the JSON string 178 179 NSLog (@ "JSONKit to convert the string: % @ ", [books JSONString]); 180 181} 182 183-(NSString *) tableView :( UITableView *) tableView184 185 titleForHeaderInSection :( NSInteger) section186 187 {188 189 return tableTitle; 190 191} 192 193-(NSInteger) tableView :( UITableView *) tableView194 195 numberOfRowsInSection: (NSInteger) section196 197 {198 199 // how many objects are contained in parseResult, this table shows how many rows 200 201 retrun [parseResult count]; 202 203} 204 205-(UITableViewCell *) tableView :( UITableView *) tableView206 207 cellForRowAtIndexPath :( NSIndexPath *) indexPath208 209 {210 211 // retrieve reusable cells based on the ID of the dynamic cell prototype 212 UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: @ "bookCell" 213 214 forIndexPath: indexPath]; 216 217 // obtain the data corresponding to the current row number in parserResult 218 NSDictionary * book = [parseResult objectAtIndex: indexPath. row]; 220 221 // get the three controls in the cell and set the display text 222 223 UILabel * titleLabel = (UILabel *) [cell viewWithTag: 1] for the three controls; 224 225 titleLabel. text = [book objectForKey: @ "title"]; 226 227 UILabel * authorLabel = (UILabel *) [cell viewWithTag: 2]; 228 229 authorLabel. text = [book objectForKey: @ "author"]; 230 231 UILabel * remarkLabel = (UILabel *) [cell viewWithTag: 2]; 232 233 authorLabel. text = [book objectForKey: @ "remark"]; 234 235} 236 237 @ end |