Prerequisite: configure it to a specific project.
Copy the touchjson framework source code to your project. Copy the touchjson/source directory and files to the project, when adding to a project, confirm that the "Copy items into destination groups folder (if needed)" item is selected.
Convert JSON data to an object-resolution and deserialization
First introduce the file: # import "cjsondeserializer. H" to the specific source file of the project.
Then, you can convert an nsdata object containing JSON data into an object.
Nsdata * thejsondata =/* Here is some JSON data */
Nserror * theerror = nil;
Id theobject = [[cjsondeserializer deserializer] deserializeasdictionary
: Jsondata error: & error];
The class (ID theobject) of the returned object depends on the type of the JSON data. If this object is null, the parsing fails. You need to check the parameter error.
The following is the sample code of the parsing process:
Nsstring * jsonstringsrc = @ "JSON string read from a file or obtained from the network"; nsdata * jsondata = [jsonstringsrc datausingencoding: nsutf8stringencoding]; nserror * error = nil; nsdictionary * dictionary = [[cjsondeserializer deserializer] deserializeasdictionary: jsondata error: & error];
The code above converts a string containing a JSON data dictionary into an nsdictionary object. In the preceding example, if the JSON root object is not a dictionary, the deserialization operation fails.
Convert an object to JSON data-that is, generate and serialize the object
First introduce the file: # import "cjsondataserializer. H" to the specific source file of the project.
Then, a specific object can be serialized into a JSON data.
Nsdictionary * dictionary = [nsdictionary dictionarywithobject: @ "B"
Forkey: @ "A"];
Nserror * error = NULL;
Nsdata * jsondata = [[cjsonserializer serializer] serializeobject: Dictionary
Error: & error];
Nsstring * jsonstring = [[nsstring alloc] initwithdata: jsondata encoding: nsutf8stringencoding];
Nslog (@ "% @", jsonstring );