JSON format data generation and parsing for IOS development, json format for ios development

Source: Internet
Author: User

Generation and analysis of JSON format data developed by IOS, json format developed by IOS

 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 use JSON format data?
3. How to generate data in JSON format?
4. How to parse the data in JSON format?
The JSON format replaces xml to bring great convenience to network transmission, but it does not have a clear view of xml, especially when the json data is very long, we will fall into the 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 characteristics make JSON an ideal data exchange language. It is easy for people to read and write, and it is also easy for machine to parse and generate (generally used to increase the network transmission rate).

JSON data has two main data structures, one is key / value, and the other is represented in the form of an array.

1. The writing format of JSON data is: name / value pairs. Such as:
{"firstName": "Brett", "lastName": "McLaughlin", "email": "aaaa"}
 

2. The writing format of JSON data is: array format. When a set of values needs to be expressed, 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 use JSON format data?
JSON can convert a set of data represented in a JavaScript object into a string, and then you can easily pass this string between functions, or pass the string from a Web client to a server-side program in an asynchronous application. This string looks a little weird, but JavaScript can easily interpret it, and JSON can represent a more complex structure 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 transmitted as a data packet format, because JSON does not require strict closing tags like XML, which greatly increases the ratio of effective data to the total data packet, thereby reducing the same data traffic. Next, the transmission pressure of the network.

 

 3. How to generate data in JSON format? 1. Use the dictionary NSDictionary to convert to key / value format data.
// If an object other than NSString, NSNumber, NSArray, NSDictionary, or NSNull is stored in the array or dictionary, it cannot be directly saved as a file, nor can it be serialized into JSON data.
    NSDictionary * dict = @ {@ "name": @ "me", @ "do": @ "something", @ "with": @ "her", @ "address": @ "home"};
    
    // 1. Determine whether the current object can be converted into 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
         * /
        // Write JSON data to a file
        // Add a suffix to the file: Tell others about the type of the current file.
        // Note: AFN determines the data type by the file type! If you don't add the type, it may not be recognized! It is best to add the file type yourself.
        [jsonData writeToFile: @ "/ Users / SunnyBoy / Sites / JSON_XML / dict.json" atomically: YES];
        
        NSLog (@ "% @", [[NSString alloc] initWithData: jsonData encoding: NSUTF8StringEncoding]);
        
    } else {
        
        NSLog (@ "Failed to generate JSON data, please check the data format");
        
    }
 

 2. The array can be converted through JSON serialization, but the conversion result is not a 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 (@ "Failed to generate JSON data, please check the data format");
        
    }
 

 

4. How to parse the data in JSON format? 1. Use TouchJSon parsing method: (import package: #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"];

// Define an NSError object to capture error information
NSError * error;
NSString * jsonString = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: & error];

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

// Store the parsed content in the dictionary, the encoding format is UTF8, to prevent garbled characters when taking values
NSDictionary * rootDic = [[CJSONDeserializer deserializer] deserialize: [jsonString dataUsingEncoding: NSUTF8StringEncoding] error: & error];

// Because the returned Json file has two layers, go to the second layer and put it in 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: (requires import package: #import "SBJson / SBJson.h")
// Use SBJson to 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 objectForKe
y: @ "city"], [weatherInfo objectForKey: @ "weather1"], [weatherInfo objectForKey: @ "temp1"]]);
  

3. Use IOS5's own parsing class NSJSONSerialization method to parse: (no need to import packages, IOS5 support, low version IOS does not support)
// Request data from China Weather Forecast Network
    NSURL * url = [NSURL URLWithString: @ "http://www.weather.com.cn/adat/sk/101010100.html"];
    
    // create request
    NSURLRequest * request = [NSURLRequest requestWithURL: url];
    
    [[[NSURLSession sharedSession] dataTaskWithRequest: request completionHandler: ^ (NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // In the Block callback completed by the network, an error mechanism should be added.
        // Failure mechanism: wrong status code!
        
        // The simplest error handling mechanism:
        if (data &&! error) {
            
            // The JSON format is converted into a dictionary, and the analysis class NSJSONSerialization is included in IOS5 to parse out the data from the response and put it in the dictionary
            id obj = [NSJSONSerialization JSONObjectWithData: data options: 0 error: NULL];
            
            NSDictionary * dict = obj [@ "weatherinfo"];
            
            NSLog (@ "% @ ---% @", dict, dict [@ "city"]);
        }
        
    }] resume];
 

4. Analysis method using JSONKit: (requires import package: #import "JSONKit / JSONKit.h")
// If json is "single layer", that is, value is a string or number, 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 the json is nested, that is, there are array and object in the value, if you use objectFromJSONString again, the program may report an error (test results indicate that when using the json generated by the network or the obtained php / json_encode, an error will be reported, but it is defined using NSString Json string, the parsing is successful), it is best to use objectFromJSONStringWithParseOptions:
NSString * json2 = @ "{\" a \ ": 123, \" b \ ": \" abc \ ", \" c \ ": [456, \" hello \ "], \" d \ ": { \ "name \": \ "张三 \", \ "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 analysis methods in 4:

The analysis speed of the system's API is the fastest.

The parsing speed of SBJSON is the penultimate difference.

Closer to the system API is JSONKit.

In the future development process, it is recommended to choose the system's API or JSONKit to parse the JSON data.

 

If there are any mistakes in this article, please feel free to make corrections and share with you, thank you!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.