Convert between JSON String and NSDictionary/NSArray
In iOS, the NSJSONSerialization class of Objective C is used to convert between JSON strings and objects, such as NSDictionary
and NSArray
, etc.
Convert NSDictionary/NSArray to JSON
Use dataWithJSONObject:options:error: method.
There are 4 values for NSJSONWriting
.
1. NSJSONWritingPrettyPrinted
The writing option that uses white space and indentation to make the output more readable.
2. NSJSONWritingSortedKeys
The writing option that sorts keys in lexicographic order.
3. NSJSONWritingFragmentsAllowed
4. NSJSONWritingWithoutEscapingSlashes
// NSDictionary
NSDictionary *dictionaryOrArray = @{@"value": @"blue", @"key": @"color"};
// NSArray
// NSArray *dictionaryOrArray = @[@"color", @"blue"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArray
options:NSJSONWritingPrettyPrinted
error:&error];
if (error) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"%@", jsonString);
}
Convert JSON String to NSDictionary/NSArray
Use JSONObjectWithData:options:error: function.
There are 4 values for NSJSONReading
.
1. NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
2. NSJSONReadingMutableLeaves
Specifies that leaf strings in the JSON object graph are created as instances of NSMutable
.
3. NSJSONReadingAllowFragments
Specifies that the parser should allow top-level objects that are not an instance of NSArray
or NSDictionary
.
4. NSJSONReadingFragmentsAllowed
NSJSONReadingAllowFragments
and NSJSONReadingFragmentsAllowed
, which can convert @"32"
to NSNumber
32, or convert @"\"32\""
to NSString
@"32"
.
NSString *jsonString = @"{ \"colors\": [ \"red\", \"green\" ] }";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments
error:&error];
if (error) {
NSLog(@"Got an error: %@", error);
} else {
NSLog(@"%@", data);
}