Reputation: 858
I have the following JSON from a Web service:
[
"{
"count":2,
"offers":{
"0":{
"nodeID":"654321",
"publicationDate":"1396272408",
"title":"My first title",
"locations":"New York City"
},
"1":{
"nodeID":"123456",
"publicationDate":"1396272474",
"title":"My second title",
"locations":"San Diego"
}
},
"error":"null",
"result":"success"
}"
]
I need to map this JSON to a NSDictionary
. How can I do that?
I already tried the following
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
but it only gives me a dictionary with one object in it. I need to access all the fields of the JSON such as "count"
, "offers"
etc. How can I achieve this?
Upvotes: 1
Views: 1007
Reputation: 985
Get your data in this form ... Your json Give error of ".....
[
{
"count": 2,
"offers":
{
"0": {
"nodeID": "654321",
"publicationDate": "1396272408",
"title": "Myfirsttitle",
"locations": "NewYorkCity"
},
"1": {
"nodeID": "123456",
"publicationDate": "1396272474",
"title": "Mysecondtitle",
"locations": "SanDiego"
}
},
"error": "null",
"result": "success"
}
]
You get data In Array [ having Dictionary in dictionary ....
Upvotes: 0
Reputation: 69499
You JSON output is not a dictionary but an array.
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSarray *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
for(NSDictionary *dict in parsedObject) {
NSNumber *count = [dict objectForKey:@"count"];
}
But the offer node is just weird, this would be better as an array.
Upvotes: 1