JSON

JSON(JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript (the JS specification of the European Computer Association) and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clarity of the hierarchy make JSON an ideal data exchange language. Easy to read and write, but also easy to machine parsing and generation, and effectively improve the efficiency of network transmission.

JSON, brief

JSON was born because the details of XML integration into HTML vary from browser to browser, so Douglas Crockford and Chip Morningstar worked together to extract a subset of THE JS data types, As a new data interchange format, there were no compatibility issues when parsing the new data format because the mainstream browsers used common JavaScript engine components, so they named the data format “JavaScript Object Notation”, or JSON, JSON was born!

The six data types of JOSN

    1. String: a String. It must be enclosed in double quotation marks. Such as:
"[{\"y\":2019,\"m\":10,\"d\":2},{\"y\":2019,\"m\":10,\"d\":4}]"
Copy the code
    1. Number: A Number, consistent with the JavaScript Number. Integers (without decimals or exponents) can have up to 15 digits, and decimals can have up to 17 digits. Such as:
{ "age"30} :Copy the code
    1. Object: a JavaScript Object. {key:value} can be nested. Such as:
{
   "name":"runoob"."alexa": 10000,"sites": {
       "site1":"www.runoob.com"."site2":"m.runoob.com"."site3":"c.runoob.com"
   }
Copy the code
    1. Array: Array. The JavaScript Array representation [value] can be nested. Such as:
Arrays can contain multiple objects: {"sites": [{"name":"Rookie Tutorial" , "url":"www.runoob.com" }, 
{ "name":"google" , "url":"www.google.com" }, 
{ "name":"Weibo" , "url":"www.weibo.com"}]} // Separate json array ["Google"."Runoob"."Taobao" ]
Copy the code
    1. True /false: Boolean type, JavaScript Boolean type. Such as:
{ "flag":true }
Copy the code
    1. Null: null, JavaScript null. Such as:
{"myCount": null}
Copy the code

NSJSONSerialization

An object that converts between JSON and its equivalent base object. You can use the NSJSONSerialization class to convert JSON to a base object, or to convert a base object to JSON.

An underlying object that can be converted to JSON must have the following properties:

  • The top-level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

Other rules may apply. The final attempt is made after the isValidJSONObject: method is called to determine whether a given object can be converted to JSON data.

NSJSONSerialization common functions

+ (BOOL)isValidJSONObject:(id)obj;

Function description: Returns a Boolean value indicating whether the given object can be converted to JSON data.

Parameters:

Obj: The object to test.

Return value: YES if obj can be converted to JSON data, NO otherwise.

+ (BOOL)isValidJSONObject:(id)obj;
Copy the code

+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

Return JSON data from the underlying object. If obj does not generate valid JSON, an exception is thrown. This exception is raised before parsing and indicates a programming error, not an internal error. Use the isValidJSONObject: method before calling this method to check that the input generates valid JSON.

Parameters:

Obj: Object used to generate JSON data. It must be non-nil.

Opt: Option for creating JSON data.

Error: internal error if, in return contains an NSError object that contains the code NSPropertyListWriteInvalidError describe the problem.

Return value: JSON data from obj or nil if an internal error occurs. The resulting data is encoded in UTF-8.

+ (nullable NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
Copy the code

NSJSONWritingOptions enumerates the following options for creating JSON data:

Typedef NS_OPTIONS(NSUInteger, NSJSONWritingOptions) {// Write options that use whitespace and indentation to make output more readable. // If this option is not set, generate as compact a JSON representation as possible. NSJSONWritingPrettyPrinted = (1 ul < < 0), / / in order of the dictionary keys to write options. NSJSONWritingSortedKeys API_AVAILABLE(MacOS (10.13), ios(11.0), Watchos (4.0), tVOs (11.0)) = (1UL << 1), JSON string that is neither NSArray nor NSDictionary, / / but must be valid JSON fragment NSJSONWritingFragmentsAllowed = (1 ul < < 2), / / no escaping backslash JSON write NSJSONWritingWithoutEscapingSlashes API_AVAILABLE (macos (10.15), the ios (13.0), watchos (6.0), Tvos (13.0)) = (1 ul < < 3),} API_AVAILABLE (macos (10.7), the ios (5.0), watchos (2.0), tvos (9.0));Copy the code

Example: dictionary-to-JSON string method

// dictionary to json string method -(NSString *)convertToJsonData:(NSDictionary *)dict{NSError *error; / / from the underlying object returns JSON data NSData * jsonData = [NSJSONSerialization dataWithJSONObject: dict options: NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString;if(! jsonData) { NSLog(@"% @",error);
        
    }else{ jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; } NSMutableString *mutStr = [NSMutableString stringWithString:jsonString]; NSRange range = {0,jsonString.length}; / / remove the Spaces in the string [mutStr replaceOccurrencesOfString: @"" withString:@""options:NSLiteralSearch range:range]; NSRange range2 = {0,mutStr.length}; / / remove the newline character in the string [mutStr replaceOccurrencesOfString: @"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
Copy the code

+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

Return a Foundation object from the given JSON data. The data must be one of the five supported encodings listed in the JSON specification :UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, utF-32BE. Data may or may not have a BOM. The most efficient encoding for parsing is UTF-8, so use UTF-8 if you have the option of encoding the data passed to that method.

Parameters:

Data: A data object containing JSON data.

Opt: Option for reading JSON data and creating the underlying object.

Error: if an error occurs, the return contains an NSError object, the object code for NSPropertyListReadCorruptError, used to describe the problem.

Return value: The underlying object of the JSON data conversion in the data, or nil if an error occurs.

+ (nullable id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
Copy the code

NSJSONReadingOptions enumerates the following options for reading JSON data and creating the underlying object:

Typedef NS_OPTIONS(NSUInteger, NSJSONReadingOptions) {// Specifies that arrays and dictionaries are created as mutable objects. NSJSONReadingMutableContainers = (1 ul < < 0), / / return a JSON string values for NSMutableString object. NSJSONReadingMutableLeaves = (1UL << 1), // NSJSONReadingFragmentsAllowed = (1UL << 2), JSON string outermost layer is allowed to be neither NSArray nor NSDictionary, but must be a valid JSON fragment. NSJSONReadingAllowFragments API_DEPRECATED_WITH_REPLACEMENT("NSJSONReadingFragmentsAllowed", macOS (10.7, API_TO_BE_DEPRECATED), ios(5.0, API_TO_BE_DEPRECATED), watchos(2.0, API_TO_BE_DEPRECATED), tVOs (9.0, API_TO_BE_DEPRECATED)) = NSJSONReadingFragmentsAllowed,} API_AVAILABLE (macos (10.7), the ios (5.0), watchos (2.0), tvos (9.0));Copy the code

For example, JSON strings are converted to dictionaries

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        returnnil; } / / return a NSData object, this object contains the receiver using the given coding coding representation NSData * jsonData = [jsonString dataUsingEncoding: NSUTF8StringEncoding]; NSError *err; / / from the given the JSON data returned a Foundation NSDictionary object * dic = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingMutableContainers error:&err];if(err)
    {
        NSLog(@"Json parsing failed: %@",err);
        return nil;
    }
    return dic;
}
Copy the code