Http://blog.sina.com.cn/s/blog_7b9d64af0101ce92.html
Click to open the link
In iOS 5, Apple introduced a nsjsonserialization class that parses a JSON string. Through this class, we can accomplish the transformation between JSON data and Nsdictionary and Nsarray.
In the past, I remember using a third party plugin. However, after the Apple out of this set of analysis, the efficiency is greatly exceeded, all the analytic third party class library. Therefore, it is recommended to use the Nsjsonserialization class to complete the transformation.
First, convert nsdictionary or Nsarray into a JSON string
Converts a dictionary or array into a JSON string
-(NSData *) Tojsondata: (ID) thedata{
Nserror *error = nil;
NSData *jsondata = [Nsjsonserialization datawithjsonobject:thedata
options:nsjsonwritingprettyprinted
error:&error];
if ([jsondata length] > 0 && error = = nil) {
return jsondata;
}else{
return nil;
}
}
Using this method's return, we can get the desired JSON string
NSString *jsonstring = [[NSString alloc] Initwithdata:jsondata
Encoding:nsutf8stringencoding];
convert the JSON string to Nsdictionary or Nsarray
Convert NSString to NSData
[Jsonstring datausingencoding:nsasciistringencoding];
Converts a JSON string into a dictionary or array
-(ID) toarrayornsdictionary: (NSData *) jsondata{
Nserror *error = nil;
ID jsonobject = [nsjsonserialization jsonobjectwithdata:jsondata
Options:nsjsonreadingallowfragments
error:&error];
if (jsonobject!= nil && error = = nil) {
return jsonobject;
}else{
Parse error
return nil;
}
}
encapsulation of the operation of JSON strings and Nsarray and Nsdictionary
Of course, there are many times when we define these operations in a taxonomy of NSObject and NSString, respectively.
Direct paste:
1. Convert NSString to Nsarray or nsdictionary
#import "Nsstring+jsoncategories.h"
@implementation NSString (jsoncategories)
-(ID) jsonvalue;
{
nsdata* data = [self datausingencoding:nsutf8stringencoding];
__autoreleasing nserror* error = nil;
ID result = [nsjsonserialization jsonobjectwithdata:data options:kniloptions error:&error];
if (Error!= nil) return nil;
return result;
}
@end
2. Convert Nsarray or nsdictionary to NSString
#import "Nsobject+jsoncategories.h"
@implementation NSObject (jsoncategories)
-(nsdata*) jsonstring;
{
nserror* error = nil;
ID result = [nsjsonserialization datawithjsonobject:self
Options:kniloptions error:&error];
if (Error!= nil) return nil;
return result;
}
@end
I hope it will be of some help to you.