How to parse nested JSON objects? - ios

I get the JSON format like this:
stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})
What I want to get is an array for the "ios".
This is my code:
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
NSArray *ios_data = [[[dataDict objectForKey:#"posts"] objectForKey:#"CHANNEL"] objectForKey:#"ios"];
NSLog(#"%#",ios_data);
dict = [NSDictionary dictionaryWithObjectsAndKeys:ios_data, ios,nil];
}
but it return in NULL, what the problem of it?

Your "JSON":
stream( { posts: [{CHANNEL: {ios: "(format=m3u8-aapl).m3u8"} }]})
Is not JSON. You can try running it through a validator like http://jsonlint.com/ to test it out.
Also, you should create an NSError reference to pass in instead of nil so NSJSONSerialization can vend you an error object. This will help in your debugging.
Here is an example of what your data would look like if it were valid JSON:
{
"stream": [
{
"posts": [
{
"CHANNEL": {
"ios": "(format=m3u8-aapl).m3u8"
}
}
]
}
]
}
(I spaced it out to be more legible, but the spacing is unnecessary for parsing.)

Once you have your array holding 'posts' you can drill down like this:
NSArray *fileData = [myDic1 valueForKeyPath:#"posts.CHANNEL"];
and then access like this:
for (int i=0; i < [clientFileData count]; i++) {
NSDictionary *myDictionary = [fileData objectAtIndex:i];
]
Also, unless I am wrong, your JSON file seems incorrectly formatted.

Get your response like:
NSDictionary *dictionaryData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
Correct JSOn should be like this
{
"posts":[
{
"CHANNEL":{
"ios":"(format=m3u8-aapl).m3u8"
}
}
]
}
Get the correct format of JSON and then try to parse it. And one thing you were doing wrong is POST is an array.

Related

Converting a Dictionary with a value of [NSNull null] to JSON

I am trying to use this code:
NSDictionary *innerMessage
= #{#"nonce":[NSNumber numberWithInteger:nonce],
#"payload":#{#"login": [NSNull null]}};
NSError * err;
NSData * innerMessageData = [NSJSONSerialization
dataWithJSONObject:innerMessage options:0
error:&err];
to create a JSON object with the following structure:
{
"apikey": "e418f5b4a15608b78185540ef583b9fc",
"signature": "FN6/9dnMfLh3wZj+cAFr82HcSvmwuniMQqUlRxSQ9WxRqFpYrjY2xlvDzLC5+qSZAHts8R7KR7HbjiI3SzVxHg==",
"message":{
"nonce": 12,
"payload": {
"Login": {}
}
}
}
However, this is the actual result which I get:
{"nonce":1398350092512,"payload":{"login":null}}
Why is [NSNull null] in my dictionary not being converted to {}?
How would I need to change my code to get the correct JSON
structure?
Thank you!
NSNull is suppose to become null in the JSON.
If you want an empty dictionary in the JSON ({}) you should use an empty dictionary - #{}.
Change code to
NSDictionary *innerMessage = #{
#"nonce":#12,
#"payload":#{#"login": #{}}
};
NSError * err;
NSData * innerMessageData = [NSJSONSerialization
dataWithJSONObject:innerMessage options:0
error:&err];
This will create the desired response
{
nonce = 12,
payload = {
login = {}
},
}
null is a perfectly valid JSON value; what were you expecting? How should NSJSONSerialization know that you wanted [NSNull null] to be converted to an empty object? (For that matter, why wouldn’t nulls be converted to an empty array, an empty list, or numeric zero?)
The solution is to process your innerMessage before you serialize it, replacing any instances of [NSNull null] with #{} (or, equivalently, [NSDictionary dictionary]).

Xcode - Getting object out of an array within an array

I have a JSON array(dictionary?) of objects that are themselves an array. I need to find a value within one of these arrays so that I can compare it later. Part of my JSON data:
[
{
"Name": "Exhibitor",
"Url": "api/congress/exhibitor",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Workshop",
"Url": "api/congress/workshop",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Speaker",
"Url": "api/congress/Speaker",
"ResourceType": "Data",
"LastMod": 1389106977
},
]
My method receives a table name as a parameter and returns a time stamp. How would I receive the time stamp (1389106977) for the table "workshop" for example? This seems so simple but I cannot work it out for 'nested' arrays/dictionaries.
Thanks,
edit:
This is the my code with trojanfoe's added to it.
NSError* localError;
NSMutableArray *syncDataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (syncDataArray)
{
NSNumber *lastMod = nil;
for (NSDictionary *dict in syncDataArray)
{
NSLog(#"current table is: %#", dict[#"Name"]);
if ([tableName isEqualToString:dict[#"Name"]])
{
lastMod = dict[#"LastMod"];
//break;
}
}
NSLog(#"LastMod = %#", lastMod);
}
else
{
NSLog(#"syncDataArray is empty");
}
This works perfectly and makes sense
The JSON data looks like an array of dictionaries, so you can iterate over the array and test for the "Name" entry:
NSArray *jsonData = ...; // You have converted JSON to Objective-C objects already
NSNumber *lastMod = nul;
for (NSDictionary *dict in jsonData) {
if ([#"Workshop" isEqualToString:dict[#"Name"]]) {
lastMod = dict[#"LastMod"];
break;
}
}
if (lastMod) {
// You found it
}
(Note I am not certain the type of object used to store the "LastMod" object, so you might need to do some debugging to find out).
EDIT If you make extensive use of this data you should immediately convert the JSON data into an array of (custom) model objects, which will make it easier to manipulate the data as your app becomes more complex.
You have an array for dictionaries so it would look something like :
NSNumber *timestamp = [[JSON objectAtIndex:index] objectForKey:#"LastMod"];
NSNumber *timestamp = response[1][#"LastMod"];

JSon parsing error IOS with empty object key

Hi I have this JSON I'm trying to parse using NSDictionary and trying to get the values as mentioned . but the problem is i do not get a key when i further go into the JSON is there any way to remove this key to go more deep.
NSDictionary *Allinfo = [json objectForKey:#"Collection"];//I go into "Collection"
NSLog(#"All with response array: %#", Allinfo);
NSDictionary *datainfo = [Allinfo objectForKey:#"contact"];//i go into "contact"
after which i get
Data : (
{
attributeList = {
attribute = (
{
name = "display-name";
value = "tel:+";
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
},
{
attributeList = {
attribute = (
{
name = "display-name";
value = bob;
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
}
)
This starts from a { and i do not get a key for the next object so that i can get the values inside the JSOn
Is there any easier way to remove this or any other so that i can get values like name and value and store them in an array.
Thanks in advance
You have keys for all.
In fact you seem to get confused on array which is a part of attribute.
The outermost key is Data which contains array.
For each object of the array you have :
The first key is attributeList & contactD.
The value of attribute key is an array of 3 values. Each array contains key value pairs. keys are name & value.
I am not sure from where you got [Allinfo objectForKey:#"contact"]. Try to parse like below..
NSDictionary *Allinfo = [json objectForKey:#"Collection"];
NSArray *dataArray = [Allinfo objectForKey:#"Data"];
for(NSDictionary *dic in dataArray)
{
NSDictionary *attributeList=[dic objectForKey:#"attributeList"];
NSArray *attributeArray=[attributeList objectForKey:#"attribute"];
NSString *resourceURLString=[attributeList objectForKey:#"resourceURL"];
NSString *contactIdString=[dic objectForKey:#"contactId"];
for(NSDictionary *attributeDic in attributeArray)
{
NSString *nameString=[attributeDic objectForKey:#"name"];
NSString *valueString=[attributeDic objectForKey:#"value"];
}
}
You can use the following method for this
NSError *e = nil;
NSArray *itemArray = [NSJSONSerialization JSONObjectWithData:[response dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (!itemArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in itemArray) {
//Your Data
}
}

Putting JSON into an Array

I'm a noob when it comes to requests and JSON. Inside my app I send to the server and get back stuff so I can use it of course. I tried looking up different things but none really seem to be what I'm looking for. So I'm getting back what seems to be formatted JSON. What I want to know how to do is put it into a NSMutable array. The way I get this JSON is by using AFNetworking's AFJSONRequestOperation.
My response looks like this.
{
id = 38;
name = "St. Martin Hall";
},
{
id = 40;
name = "Assumptions Commons";
},
{
id = 41;
name = "Vickroy Hall";
},
{
id = 42;
name = "St. Ann Hall";
},
{
id = 37;
name = "Duquesne Towers";
}
if your JSON format like {"mainKey":[{},{},...]}
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* dataArray = [json objectForKey:#"mainKey"]; //2
else your JSON format like [{},{},...]
NSError* error;
NSArray* dataArray = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
I think your format is case 2: [] Array of Object {}
Tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
JSON:http://www.json.org
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
This class is available in iOS 5.0+. If you're targetting older iOS version, have a look at a third-party JSON framework:
Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
If that's what you're getting back it's not JSON I'm afraid. It does look like Javascript in a way but it should be more like
[
{
"id" : 38,
"name" : "St. Martin Hall"
},
{
"id" : 39,
"name" : "Assumptions Commons"
}
]

Parsing JSON response with multiple objects

I've got a question regarding parsing a JSON response within iOS5.
Currently, I'm following this guide here to help me parse the JSON response returned from a third-party mapping service.
Everything works, except that the JSON response returned by the third-party server is somewhat different from the one shown in the guide itself.
In a nutshell, the overall structure of the entire JSON response looks something like this:
{
"directions": [....],
"messages": [....],
"routes":
{
"features": [
{
"attributes": {....},
"geometry":
{
"paths": [....]
}
}
]
}
}
This is the actual JSON query URL.
By using this line of code,
NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
I am able to sucessfully get the jsonResponse dictionary to report that it has 3 key/value pairs, but my ultimate goal is to retrieve the array stored in 'routes.features.geometry.paths'.
This is my current code block that gets the final set of array values:
NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray * jsonArray = [jsonResponse valueForKeyPath:#"routes.features.geometry.paths"];
jsonArray = [jsonArray objectAtIndex:0];
jsonArray = [jsonArray objectAtIndex:0];
I was wondering if anyone might have a better idea of how I should go about doing this in a more elegant fashion?
Thanks a lot in advance!
You can't just use it as JSON object because it will be working as JSON (Plain String) and you need to parse it so for your problem you can do like this to directly go to paths
NSArray *arr = [[[[jsonResponse objectForKey:#"routes"] objectForKey:#"features"] objectForKey:#"geometry"] objectForKey:#"paths"];
Now you can access your paths data from "arr" array
UPDATE:
NSArray *arr = [[[[[jsonResponse objectForKey:#"routes"] objectForKey:#"features"] objectAtIndex:0] objectForKey:#"geometry"] objectForKey:#"paths"];
as features element is an Array so traverse array first then goto its elements

Resources