It is very convenient to process JSON data under Cocoa, and the core object is nsjsonserialization, which can accomplish the conversion between JSON data and the Foundation object. Convert the JSON data to the Foundation object, using Jsonobjectwithdata. Convert the Foundation object to JSON data, using Datawithjsonobject. This class also supports the input and output of streams.
Objects converted to JSON must have the following properties:
- The top-level object must be Nsarray or nsdictionary.
- All objects must be instances of NSString, NSNumber, Nsarray, Nsdictionary, and NSNull.
- All nsdictionary keys must be of type NSString.
- Numeric objects cannot be non-numeric or infinite.
Fortunately, JSON data types are basically strings and integers. For integer and Boolean values, the Cocoa is encapsulated in NSNumber, so the Boolean value in JSON needs to be obtained with the boolvalue of NSNumber.
For example, simplify the code:
Nsdictionary *jsondict = @{@"name":@"Catshit",@"ID":@1,@"Extras":@{@"Color":@"Black",@"Active": @YES,@"option": [NSNullNULL]}}; NSData*data = [nsjsonserialization datawithjsonobject:jsondict options:0Error:nil]; NSLog (@"%@", [[NSString Alloc]initwithdata:data encoding:nsutf8stringencoding]);
Output JSON string:
{"Name": "Catshit", "id": 1, "extras": {"color": "Black", "option": null, "Active": true}}
When you convert a Foundation object to JSON data, you can use Isvalidjsonobject to determine whether the conversion succeeds.
Parse through Jsonobjectwithdata:
@" {\"name\": \ "catshit\", \ "id\": 1, \ "Extras\": {\ "color\": \ "Black\", \ "active\": true, \ "option\": null}}"*jsondict = [Nsjsonserialization jsonobjectwithdata:[jsonstring Datausingencoding:nsutf8stringencoding] Options:0 Error:nil];
NSLog (@ "name =%@", [jsondict valueforkey:@ "name"]);
Jsonobjectwithdata actually returns an ID, because the top layer is probably nsarray or nsdictionary, and for this example, the top level is a dictionary.
With KVC, it is also convenient to access nested data, such as if you want to directly access the extras under active or not, you can:
NSNumber *active = [jsondict valueforkeypath:@ "extras.active"]; if ([Active Boolvalue]) { ... }
Isn't it simple? Nsjsonserialization is present in both Cocoa and Cocoa Touch and is a very small and convenient class for processing JSON.
JSON data processing under the Cocoa