On the generation and analysis of JSON format data developed by iOS

  • 2021-09-11 21:37:20
  • OfStack

This article will explain the generation and analysis of JSON format data in IOS development from four aspects:

1. What is JSON?

2. Why do we need data in JSON format?

3. How to generate data in JSON format?

4. How to parse data in JSON format?

JSON format replaces xml, which brings great convenience to network transmission, but it is not as clear as xml, especially when json data is very long, we will fall into tedious and complicated data node search. At this time, we need an online verification tool BeJson.

1. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript. JSON uses a completely language-independent text format, but also uses habits similar to the C language family (including C, C + +, C #, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language. Easy to read and write, but also easy to machine analysis and generation (1 is generally used to improve the network transmission rate).

JSON data mainly has two data structures, one is key/value, and the other is array.

1. The writing format of JSON data is: name/value pair. Such as:


{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"} 

2. The writing format of JSON data is array format. When it is necessary to represent a group of values, JSON can not only improve readability, but also reduce complexity. Such as:


{
  "programmers": [{
    "firstName": "Brett",
    "lastName": "McLaughlin",
    "email": "aaaa"
  }, {
    "firstName": "Elliotte",
    "lastName": "Harold",
    "email": "cccc"
  }],
  "authors": [{
    "firstName": "Isaac",
    "lastName": "Asimov",
    "genre": "sciencefiction"
  }, {
    "firstName": "Frank",
    "lastName": "Peretti",
    "genre": "christianfiction"
  }],
  "musicians": [{
    "firstName": "Eric",
    "lastName": "Clapton",
    "instrument": "guitar"
  }, {
    "firstName": "Sergei",
    "lastName": "Rachmaninoff",
    "instrument": "piano"
  }]
}

2. Why do we need data in JSON format?

JSON converts a set of data represented in an JavaScript object into a string, which can then be easily passed between functions or from an Web client to a server-side program in an asynchronous application. This string may seem odd, but JavaScript is easy to interpret, and JSON can represent more complex structures than "name/value pairs." For example, you can represent arrays and complex objects, not just simple lists of keys and values.

JSON has higher efficiency when transmitting as a data packet format, because JSON does not need strict closed labels like XML, which greatly improves the ratio of effective data volume to total data packets, thus reducing the transmission pressure of the network under the same data flow.

3. How to generate data in JSON format?

1. Use dictionary NSDictionary to convert data into key/value format.


//  If an array or dictionary stores  NSString, NSNumber, NSArray, NSDictionary, or NSNull  Objects other than , You can't save it as a file directly . Nor can it be serialized into  JSON  Data .
  NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
  
  // 1. Determines whether the current object can be converted to JSON Data .
  // YES if obj can be converted to JSON data, otherwise NO
  BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
  
  if (isYes) {
    NSLog(@" Can be converted ");
    
    /* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8.
     */
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    
    /*
     Writes the bytes in the receiver to the file specified by a given path.
     YES if the operation succeeds, otherwise NO
     */
    //  Will JSON Write data into files 
    //  Add suffix name to file :  Tell others the type of current file .
    //  Attention : AFN The data type is determined by the file type ! If you do not add a type , It may not be recognized !  It is best to add file types yourself .
    [jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
    
    NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    
  } else {
    
    NSLog(@"JSON Data generation failed, please check data format ");
    
  }

2. Arrays can be converted by JSON serialization, but the conversion result is not in the standardized JSON format.


     NSArray *array = @[@"qn", @18, @"ya", @"wj"];
  
  BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
  
  if (isYes) {
    NSLog(@" Can be converted ");
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
    
    [data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
  
  } else {
    
    NSLog(@"JSON Data generation failed, please check data format ");
    
  }

4. How to parse data in JSON format?

1. Use TouchJSon parsing method: (Package to be imported: # import "TouchJson/JSON/CJSONDeserializer. h")


// Use TouchJson To analyze the weather in Beijing 
// Get API Interface 
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];

// Definition 1 A NSError Object for capturing error messages 
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

NSLog(@"jsonString--->%@",jsonString);

// The parsed content is stored in the dictionary, and the encoding format is UTF8 To prevent random code when taking values 
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];

// Because the returned Json The document has two layers, go to the first 2 Layer contents are put into the dictionary 
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);

// Value printing 
NSLog(@"%@",[NSString stringWithFormat:@" Today is  %@ %@ %@  The weather conditions are: %@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);

2. Use SBJson parsing method: (Package to be imported: # import "SBJson/SBJson. h")


// Use SBJson Analyze the weather in Beijing 
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];

NSError *error = nil;

NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];

SBJsonParser *parser = [[SBJsonParser alloc] init];

NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];

NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];

NSLog(@"%@", [NSString stringWithFormat:@" Today is  %@ %@ %@  The weather conditions are: %@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);

3. Use IOS5's own parsing class NSJSONSerialization method to parse: (No import package is required, IOS5 supports it, but lower version IOS does not support it)


//  Request data from China Weather Forecast Network 
  NSURL *url = [ NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
  
  //  Create a request 
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  
  [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    
    //  Completed on the network  Block  In callback , To add an error mechanism .
    //  Failure mechanism handling :  Error status code !
    
    //  The simplest error handling mechanism :
    if (data && !error) {
      
      // JSON Format is converted into a dictionary, IOS5 With its own parsing class in NSJSONSerialization From response Put the data parsed in the dictionary 
      id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
      
      NSDictionary *dict = obj[@"weatherinfo"];
      
      NSLog(@"%@---%@", dict, dict[@"city"]);
    }
    
  }] resume];

4. Parsing method using JSONKit: (Package to be imported: # import "JSONKit/JSONKit. h")


// If json Is "single layer", that is, value They are all strings and numbers, and you can use objectFromJSONString
NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
NSLog(@"json1:%@",json1);

NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);

// If json There is nesting, that is, value There are array , object If you use it again objectFromJSONString The program may report an error (test results show that it uses the php/json_encode Generated json An error is reported, but an error is reported using the NSString Defined json String, parsing succeeds), it is best to use objectFromJSONStringWithParseOptions : 
NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\" Zhang 3\", \"age\":\"32\"}}";
NSLog(@"json2:%@", json2);

NSDictionary *data2 = [json2 objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);

Friendly Tips:

Comparison of parsing methods in 4:

The API of the system has the fastest parsing speed.

The resolution speed of SBJSON is the second lowest difference.

Closer to the system API is JSONKit.

In the future development process, it is suggested to choose API or JSONKit of the system to analyze JSON data.


Related articles: