In iOS 5, Apple introduced a nsjsonserialization class that parses the JSON string .
With this class, we can complete the JSON data with The transformation between Nsdictionary and Nsarray. Previously, I remembered that I was using a third-party plugin. However, Apple out of this set of analysis, efficiency also greatly exceeded, all the analytic third-party class library. Therefore, it is recommended to useNsjsonserialization class to complete the conversion.
First, convert nsdictionary or Nsarray to JSON string
Convert 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 the return of this method, we can get the JSON string we want.
NSString *jsonstring = [[nsstring alloc] initwithdata:jsondata
encoding:nsutf8stringencoding];
Second, the
JSON string
translates to
nsdictionary or nsarray WillNSString converted 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) {
Returnjsonobject;
}else{
// Parse error
return nil;
}
}
third, the JSON string and the Nsarray and
nsdictionary operation for encapsulationOf course, there are many times when we define these operations, respectively, inin a taxonomy of NSObject and NSStringDirect stickers:
1. Convert nsstring to Nsarray or nsdictionary
#import "Nsstring+jsoncategories.h"
@implementationNSString (jsoncategories)
-(ID) jsonvalue;
{
nsdata* Data =[selfdatausingencoding: nsutf8stringencoding];
__autoreleasing nserror* error= nil;
IDresult = [nsjsonserializationjsonobjectwithdata:d ataoptions: Kniloptionserror:& ERROR];
if (Error! = nil) return nil;
return result;
}
@end
2. Place Nsarray or nsdictionary
translates to
NSString
#import "Nsobject+jsoncategories.h"
@implementation NSObject (jsoncategories)
-(nsdata*) jsonstring;
{
nserror* error = nil;
IDresult = [nsjsonserializationdatawithjsonobject: Self
options:kniloptions error:&error];
if (Error! = nil) return nil;
return result;
}
@end
Conversion between Nsjsonserialization-json data and Nsdictionary and Nsarray