iOS Development Network Chapter One-to-One JSON Resolution

1. What is JSON?

1). JSON is a lightweight data format commonly used for data interaction.

2). Data returned by the server to the client, usually in JSON or XML format (except file downloads)

3). JSON is formatted much like dictionaries and arrays in OC

{ "name" : "jack" , "age" :  10 }

{ "names" : [ "jack" , "rose" , "jim" ] }

Note for standard JSON format: key must be double quoted


2. Serialization and Deserialization

Serialization: OC Object---> JSON/XML

Deserialization: JSON/XML ---> OC Object


Convert Table

     JOSN   OC

     {}       @{}

     []       @[]

     ""       @""

     false    NSNumber 0

     true     NSNumber 1

* null * NSNull is empty


JSON parsing scheme:

a. Third-party framework JSONKit\SBJSONTouchJSON

b. Apple native (NSJSONSerialization) performs best

Common methods for NSJSONSerialization:

JSON Data - > OC Object
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;

OC Object - > JSON Data 
+ (NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;

Is OC object rotatable
+ (BOOL)isValidJSONObject:(id)obj;



Note: The following code includes:

1. Serialization (OC Object---> JSON Data)

Note: Not all OC objects can be converted to JSON(NSString type is not possible)

Requirements for serialization:

- The outermost layer must be NSArray or NSDictionary

- All elements must be NSString, NSNumber, NSArray, NSDictionary, or NSNull

        -All key s in the dictionary must be of type NSString

* NSNumbers cannot die to infinity


If the above requirements are not met: In order to prevent the program from crashing, it is necessary to make a judgment whether the oc object can be converted to JSON.

    // Determine if oc object can rotate
    BOOL isValid = [NSJSONSerialization isValidJSONObject:dictM];
    if (!isValid) {
        NSLog(@"%zd",isValid);
        return;
    }


2. Deserialization (JSON Data---> OC Objects)

Note: If you are parsing non-dictionary/array data, you can only use the NSJSONReadingAllowFragments enumeration

kNilOptions == 0


3. Relationship between JSON and OC objects

4. plist data to JSON data

//
//  ViewController.m
//  05 Master-JSON parsing
//
//  Created by Chaoyang on 2017/12/7.
//  Copyright_2017 sunny. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self OCToJson];
}

// Serialization (OC Object--> JSON)
- (void)OCToJson
{
    NSDictionary *dictM = @{
                            @"name" : @"ZY",
                            @"age" : @19
                            };
    NSArray *arrayM = @[@"44",@"123"];
    // Note: Not all OC objects can be converted to JSON (not NSString type)
    NSString *strM = @"guizhaoyang";
    
    /*
     - The outermost layer must be NSArray or NSDictionary
     - All elements must be NSString, NSNumber, NSArray, NSDictionary, or NSNull
     - All key s in a dictionary must be of type NSString
     - NSNumbers Can't die to infinity
     */
    // Determine if oc object can rotate
    BOOL isValid = [NSJSONSerialization isValidJSONObject:dictM];
    if (!isValid) {
        NSLog(@"%zd",isValid);
        return;
    }
    /*
     param1:OC object to be converted
     param2: Typography, beautiful NSJSONWriting PrettyPrinted
     param3:error message
     */
    NSData *data = [NSJSONSerialization dataWithJSONObject:dictM options:NSJSONWritingPrettyPrinted error:nil];
    NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}

// Deserialization (JSON --> OC object)
- (void)JsonToObject
{
    //1. Determine the URL
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    //2. Create Request Object
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    //3. Send asynchronous requests
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        // Data (Response Body) --->is essentially a string
        //4. Parse data
        // Deserialize JSON--->OC Objects
        /*
         NSJSONReadingMutableContainers = (1UL << 0), Returns a variable dictionary and array
         NSJSONReadingMutableLeaves = (1UL << 1), iOS7 If you have problems later, you will not need to
         NSJSONReadingAllowFragments = (1UL << 2) The parsed data is neither a dictionary nor an array and must use this enumeration value
         */
        
        // kNilOptions == 0
        //       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        //        NSLog(@"%@",dict[@"success"]);
        
        // If you parse data that is not a dictionary/array, you can only use the NSJSONReadingAllowFragments enumeration
        NSString *strM = @"\"GZY\"";
        id obj = [NSJSONSerialization JSONObjectWithData:[strM dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@--%@",[obj class],obj);
    }];
}

// The relationship between JSON and OC objects
- (void)JsonWithObject
{
    //NSString *strM = @"{\"error":" User name does not exist \"}";
    //NSString *strM = @"[\"error\", \" username does not exist \"]";
    //NSString *strM = @"\"wendingding\"";
    //NSString *strM = @"false";
    //NSString *strM = @"true";
    NSString *strM = @"null";
    
    id obj = [NSJSONSerialization JSONObjectWithData:[strM dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:0];
    NSLog(@"%@---%@",[obj class],obj);
    
    /*
     JOSN   OC
     {}     @{}
     []     @[]
     ""     @""
     false  NSNumber 0
     true   NSNumber 1
     null      NSNull Is empty
     */
    
    //nil
    [NSNull null];   //The result of this method is a single grain, represented as empty, that can be used in a dictionary or an array
}

// plist to JSON data
- (void)plistToJson
{
    NSArray *arrayM = [NSArray arrayWithContentsOfFile:@"/Users/sunny/Desktop/photo/apps.plist"];
    //NSLog(@"%@",arrayM);
    
    // serialize
    NSData *data = [NSJSONSerialization dataWithJSONObject:arrayM options:NSJSONWritingPrettyPrinted error:nil];
    [data writeToFile:@"/Users/sunny/Desktop/apps.json" atomically:YES];
    
}

@end


Tags: JSON xml encoding

Posted on Mon, 11 May 2020 14:11:17 -0400 by nyk