iOS JSon parsing, array in array - ios

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?
Here is my json:
{
"Language": "EN",
"Place": [
{
"City": "Stockholm",
"Name": "Slussen",
"Commute": [
"Subway",
"Bus"
]
},
{
"City": "Gothenburg",
"Name": "Central station",
"Commute": [
"Train",
"Bus"
]
}
]
}
Here is my code:
NSString *textPath = [[NSBundle mainBundle] pathForResource:#"Places" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSArray* AllPlaces = [json objectForKey:#"Place"];
for(int n = 0; n < [AllPlaces count]; n++)
{
PlaceItem* item = [[PlaceItem alloc]init];
NSDictionary* place = [AllPlaces objectAtIndex:n];
item.City = [place objectForKey:#"City"];
item.Name = [place objectForKey:#"Name"];
NSDictionary* commutes = [json objectForKey:#"Commute"];
[self.placeArray addObject:(item)];
}

Your code should be:
NSArray* commutes = [place objectForKey:#"Commute"];
Thwt would give back an array holding "Subway" and "Bus".

I think the problem is the access to json, it should be place instead:
NSArray* commutes = [place objectForKey:#"Commute"];

NSArray *commutes = [place objectForKey:#"Commute"];
This will give you an NSArray with "Subway" and "Bus".

You can considerably shrink you code using KVC Collection Operators:
NSArray *commutes = [json valueForKeyPath:#"Place.#distinctUnionOfArrays.Commute"];
If you want all repeated commutes use #unionOfArrays modifier.

Related

Incorrectly parse json into NSDictionary

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
My code:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
But its output as follows.
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.
Don't use SBJSON. Use NSJSONSerialization.
Don't use valueForKey:, use objectForKey:.
You are mixing up dictionaries and arrays. Don't do that. Use NSArray for arrays.
I am revising your code for better understanding
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
More appropriate way is
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:#"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: #"text"];
NSString *textSize = [dicTextField objectForKey: #"textSize"];
}
}
}
For quick help
treat { as dictionary and [ as array.
Hope, i am helpful to you.
As your json format, [jsonDict valueForKey:#"fields"] will return an array not dictionary so your code must be
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:#"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:#"textFields"];
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:#"fields"];
NSArray *textArray=[fields objectForKey:#"textFields"] ;
NSLog(#"--- %#",textArray );
}

Get nested data from local JSON file

Now that I have the NSDictionary object JSONDictionary, how do I get the nested data inside of it?
NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:#"sAPI" ofType:#"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
NSLog(#"Dictionary: %#", JSONDictionary);
sAPI.json snippet:
{
"ss": [{
"name": "bl",
},
"ls": [{
"name": "ML",
"abbreviation": "ml",
"id": 10,
Since you asked me to do this in a comment on a different answer, I'll answer it here. To get the name value of one of the leagues, follow this
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; //root object
NSArray *sports = JSONDictionary[#"sports"]; //array containing all sports (baseball, football, etc.)
NSDictionary *baseball = sports[0]; //dictionary containing info about baseball
NSArray *baseballLeagues = baseball[#"leagues"]; //array containing all leagues for baseball
NSDictionary *MLB = baseballLeagues[0]; //dictionary for only the MLB league
NSString *MLBName = MLB[#"name"]; //the full name of the MLB
This example only works for the MLB, but can easily be changed by finding the index of the other league or sport you want to use.
Note that the square brackets used in this answer are shorthand for the following methods
dictionary[#"key"]; -short for-> [dictionary objectForKey:#"key"];
array[0]; -short for-> [array objectAtIndex:0];

json iOS parsing error

I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding

After convert JSON array to NSDictionary, what should I do?

I need to parse a JSON array in the following format:
[
{
name: "10-701 machine learning",
_id: "52537480b97d2d9117000001",
__v: 0,
ctime: "2013-10-08T02:57:04.977Z"
},
{
name: "15-213 computer systems",
_id: "525616b7807f01fa17000001",
__v: 0,
ctime: "2013-10-10T02:53:43.776Z"
}
]
So after getting the NSData, I transfer it to a NSDictionary:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", dict);
But viewing from the console, I think the dictionary is actually like this:
(
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
ctime = "2013-10-08T02:57:04.977Z";
name = "10-701 machine learning";
},
{
"__v" = 0;
"_id" = 525616b7807f01fa17000001;
ctime = "2013-10-10T02:53:43.776Z";
name = "15-213 computer systems";
}
)
What do those parenthesis in the outside mean? How should I further transfer this NSDictionary to an NSArray or an NSMutableArray of some Course objects (what I defined myself, try to represent each element of the JSON array)?
Use this code,
NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];
Then you can retrieve the values by following code,
NSString *v = [dict objectForKey:#"__v"];
NSString *id = [dict objectForKey:#"_id"];
NSString *ctime = [dict objectForKey:#"ctime"];
NSString *name = [dict objectForKey:#"name"];
The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.
I think what you really want, though, is an array of dictionaries. Something like this:
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];
After this, firstObject would contain:
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
"ctime" = "2013-10-08T02:57:04.977Z";
"name" = "10-701 machine learning";
}
And you can retrieve the information with objectForKey:
NSString *time = [firstObject objectForKey:#"ctime"];
// time = "2013-10-08T02:57:04.977Z"
Hope that helps.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources