iOS JSON format conversion __JS

Source: Internet
Author: User
Tags serialization

The common Third-party frameworks for JSON parsing are: Jsonkit, Sbjson, Touchjson, whose sex is reduced from left to right. But starting with IOS5, Apple provides native support for JSON (nsjsonserialization).
Jsonkit has stopped updating in 2012, the official said Jsonkit than the original Apple Nsjsonserialization resolution faster, the actual test of the original Apple Nsjsonserialization resolution faster.
This article only introduces the nsjsonserialization of iOS native and common jsonkit: 1, System mode JSON data parsing

parsing JSON data

        /* Deserialization: Converts binary data received from the server into a Nsdictionary/nsarray process, simplifies program development, and facilitates subsequent dictionary-turn models. The
        data must conform to the JSON format, and the container used to receive must be consistent with the outermost layer of the JSON.

        nsjsonreadingmutablecontainers  = (1UL << 0),  //container variable, nsmutabledictionary or Nsmutablearray.
        nsjsonreadingmutableleaves      = (1UL << 1),  //leaf variable, the value of the string in the returned JSON object is nsmutablestring.
        nsjsonreadingallowfragments     = (1UL << 2)   //allow the outermost layer of the JSON string to be neither Nsarray nor nsdictionary,
                                                          But it has to be a valid JSON fragment

            in the deserialization of the variable immutable, the actual use is not very good, followed by the dictionary-turn model. Therefore, the input 0 efficiency is the best. If you see the type of parameter in the future, and
        do not want to get the corresponding content, pass NULL. Incoming nil will not be mistaken.
    *

    ///Read data from local file
    nsdata *jsondata = [NSData datawithcontentsoffile:[[nsbundle mainbundle] pathforresource:@ "Jsondatafile" oftype:@ "txt"];

    Parse JSON data
    id result = [nsjsonserialization jsonobjectwithdata:jsondata options:0 error:null];

generate JSON data:

/* Serialization: Converts a dictionary or array into binary data before sending it to the server for easy network transmission.
            The object that generates the JSON data must meet the following criteria: the outermost layer of the object must be Nsarray or nsdictionary.
            All data in the container must be NSString, NSNumber, Nsarray, nsdictionary, or nsnull type.
            All keys in a dictionary are in nsstring format.

        NSNumber cannot be NaN (non-numeric) or infinity (infinity). nsjsonwritingoptions:nsjsonwritingprettyprinted = (1UL << 0) beautiful format for printing using 0 o'clock, generating

            The data format is as follows, which can be used when you send JSON data to the server.

            {"Age": 8, "score": "Add": "Beijing", "name": "Xiaoxin"} using 1 o'clock, the resulting data format is as follows, which can be used when saving JSON data locally. {"Age": 8, "score": "," Add ":" Beijing "," name ":" X Iaoxin "}///Foundation object Nsdictionary *dicitionary = @{@" name ": @" Xiaoxin ", @" age ": @8, @"

    Score ": @99, @" Add ": @" Beijing "};

    Determines whether the Foundation object can generate JSON data BOOL isValid = [Nsjsonserialization isvalidjsonobject:dicitionary]; Generate JSON numberAccording to NSData *jdata = [nsjsonserialization datawithjsonobject:dicitionary options:0 error:null]; 
2.JSONKit Method JSON Data parsing

sondecoder Mode Analysis

Reading data from a local file
    nsdata *jsondata = [NSData datawithcontentsoffile:[[nsbundle mainbundle] pathforresource:@ " Jsondatafile "oftype:@" "TXT"]];

    ID result = [[Jsondecoder decoder] objectwithdata:jsondata];

    NSLog (@ "%@%@", result, [result class]);

jsonstring Resolution

Single-layer jsonstring
    parsing
        //If JSON is "single layer", that is, value is a string, a number, you can use objectfromjsonstring

        ///single layer jsonstring data C4/>nsstring *jsonstr1 = @ "{\ A\": 123, \ "b\": \ "Abc\"} ";

        Returns the variable result using the Mutableobjectfromjsonstring method
        nsdictionary *jsonstrdic1 = [JsonStr1 objectfromjsonstring];

    Nested jsonstring resolution
    /*
            if JSON has nested, that is, the value has array, object, if you use Objectfromjsonstring, the program may error,
        Test results indicate that using JSON generated by the network or the resulting php/json_encode will have an error, but parsing succeeds when using nsstring-defined JSON strings,
        preferably with Objectfromjsonstringwithparseoptions:

        ////nested jsonstring data
        nsstring *jsonstr2 = @ "{\ A\": 123, \ "B\" : \ "Abc\", \ "c\": [456, \ "hello\"], \ "d\": {\ "name\": \ "john \", "age\": \ "32\"} ";

        Returns the variable result using the Mutableobjectfromjsonstringwithparseoptions method
        nsdictionary *jsonstrdic2 = [jsonStr2 Objectfromjsonstringwithparseoptions:jkparseoptionlooseunicode];

Generate jsonstring Data

NSString-> jsonstring

        nsstring *str1 = @ "{a\": 123, \ "b\": \ "Abc\"} ";

        The default parameter is jkserializeoptionnone,includequotes YES
        nsstring *jsonstrfromstr1 = [str1 jsonstring];

        When Includequotes is no, the encoded data outermost contains no quotes
        nsstring *jsonstrfromstr2 = [str1 jsonstringwithoptions: Jkserializeoptionnone Includequotes:no Error:nil];

    Nsarray/nsdictionary-> jsonstring

        nsdictionary *dic1 = @{@ "name": @ "Xiaoxin", @ "age": @8, @ "Info": @{@ "Score": @99, @ "Add": @ "Beijing"};

        The default parameter is Jkserializeoptionnone
        nsstring *jsonstrfromdic1 = [Dic1 jsonstring];

        NSString *jsonstrfromdic2 = [Dic1 jsonstringwithoptions:jkserializeoptionescapeunicode error:nil];

Jsondata Resolution

    Single-layer jsondata parsing

        nsdata *jsondata1 = [@ "{\ A\": 123, \ "b\": \ "Abc\"} "datausingencoding:nsutf8stringencoding];

        Returns the variable result using the Mutableobjectfromjsondata method
        nsdictionary *jsondatadic1 = [JsonData1 objectfromjsondata];

    Nested Jsondata parse

        //Read data from local file
        nsdata *jsondata2 = [NSData datawithcontentsoffile:[[nsbundle mainbundle] pathforresource:@ "Jsondatafile" oftype:@ "txt"];

        Returns the variable result using the Mutableobjectfromjsonstringwithparseoptions method
        nsdictionary *jsondatadic2 = [jsonData2 Objectfromjsondatawithparseoptions:jkparseoptionlooseunicode];

Generate Jsondata Data

NSString-> jsondata

        nsstring *str2 = @ "{a\": 123, \ "b\": \ "Abc\"} ";

        The default parameter is jkserializeoptionnone,includequotes YES
        nsdata *jsondatafromstr1 = [str2 jsondata];

        NSData *JSONDATAFROMSTR2 = [str2 jsondatawithoptions:jkserializeoptionnone includequotes:no Error:nil];

    Nsarray/nsdictionary-> jsondata

        nsdictionary *dic2 = @{@ "name": @ "Xiaoxin", @ "age": @8, @ "Info": @{@ "score": @ , @ "Add": @ "Beijing"};

        The default parameter is Jkserializeoptionnone
        nsdata *jsondatafromdic1 = [Dic2 jsondata];

        NSData *jsondatafromdic2 = [Dic2 jsondatawithoptions:jkserializeoptionescapeunicode error:nil];

Add:
Use dictionary nsdictionary to convert data into key/value formats.

If an array or dictionary stores objects other than NSString, NSNumber, Nsarray, nsdictionary, or nsnull, it cannot be saved directly to 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 to JSON data.

    YES If obj can is converted to JSON data, otherwise NO BOOL isyes = [Nsjsonserialization isvalidjsonobject:dict];

        if (isyes) {NSLog (@ "can convert"); /* JSON data for obj, or nil If a 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 as file//file add suffix Name: Tell others the type of the current file. Note: AFN is a file type to determine the data type! If you do not add a type, you may not be able to identify it!
        It's 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 (@ "JSON data generation failed, please check data format");
 }

The array can be converted by JSON serialization, but the result of the conversion is not a standardized JSON format.

Nsarray *array = @[@ "Qn", @18, @ "Ya", @ "WJ"];

    BOOL Isyes = [nsjsonserialization Isvalidjsonobject:array];

    if (isyes) {
        NSLog (@ "can convert");

        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, check data format");

    }
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.