I have a JSON string (from PHP's json_encode()
that looks like this:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
I want to parse this into some sort of data structure for my iPhone app. I guess the best thing for me would be to have an array of dictionaries, so the 0th element in the array is a dictionary with keys "id" => "1"
and "name" => "Aaa"
.
I do not understand how the NSJSONSerialization
stores the data though. Here is my code so far:
NSError *e = nil;
NSDictionary *JSON = [NSJSONSerialization
JSONObjectWithData: data
options: NSJSONReadingMutableContainers
error: &e];
This is just something I saw as an example on another website. I have been trying to get a read on the JSON
object by printing out the number of elements and things like that, but I am always getting EXC_BAD_ACCESS
.
How do I use NSJSONSerialization
to parse the JSON above, and turn it into the data structure I mentioned?
An object that converts between JSON and the equivalent Foundation objects.
Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is language-independent, easy to understand and self-describing. It is used as an alternative to XML. JSON is very popular nowadays. JSON represents objects in structured text format and data stored in key-value pairs.
Your root json object is not a dictionary but an array:
[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
This might give you a clear picture of how to handle it:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(@"Error parsing JSON: %@", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
This is my code for checking if the received json is an array or dictionary:
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(@"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(@"jsonArray - %@",jsonArray);
}
else {
NSLog(@"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(@"jsonDictionary - %@",jsonDictionary);
}
I have tried this for options:kNilOptions and NSJSONReadingMutableContainers and works correctly for both.
Obviously, the actual code cannot be this way where I create the NSArray or NSDictionary pointer within the if-else block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With