I have a mutable array stories that I'm trying to add a copy of JSON response to but it yields O stories and nothing in the array. What am I doing wrong? The JSON object is properly formatted and I can display each component individually but they will not add to the array.
NSString *str=#"http://www.foo.com/some.php";
NSURL *url=[NSURL URLWithString:str];
NSData *data=[NSData dataWithContentsOfURL:url];
NSError *error=nil;
NSMutableDictionary *response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers error:&error];
NSLog(#"Your JSON Object: %#", response);
NSLog(#"Location: %#", response[#"location"]);
NSLog(#"Service ID: %#", response[#"serviceID"]);
NSLog(#"Problem: %#", response[#"problem"]);
[stories addObject:[response copy] ];
NSLog(#"Workorders: %d", [stories count]);
NSLog(#"WO Defined: %#",stories);
There you go...try this
NSMutableArray *stories = [NSMutableArray array];
json is:
{
"Title":"Kick", "Year":"2009", "Rated":"N/A", "Released":"08 May 2009",
"Runtime":"N/A", "Genre":"Comedy, Romance, Thriller", "Director":"Reddy Surender",
"Writer":"Abburi Ravi (dialogue), Reddy Surender (screenplay), Vakkantham Vamsi (story)",
"Actors":"Ravi Teja, Ileana, Shaam, Ali",
"Plot":"A guy with an abnormal lifestyle tries to find thrill and pleasure in every work he does and finally becomes a thief.",
"Language":"Telugu", "Country":"India", "Awards":"1 nomination.",
"Poster":"N/A","Metascore":"N/A",
"imdbRating":"7.6",
"imdbVotes":"736",
"imdvid":"tt1579592",
"Type":"movie",
"Response":"True"
}
The Code is:
-(void)parseData:(NSData *)data
{
NSString *responseString = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"responseString %#",responseString);
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:data
options:(kNilOptions)
error:&error];
NSLog(#"json data == %#", json);
NSMutableArray *response =[[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
response = [json valueForKey:#"imdbRating"];
User * userObj = [[User alloc]init];
userObj.movieRating = [json valueForKey:#"imdbRating"];
[response addObject:userObj];
}
[delegate getIMDBMovie_Rating:response];
}
How to save data in bussiness model object for key imdbRating
The Json you specified is not an array. This is an NSDictionary object. Also as this is a NSDictionary you don't need to use for loop.
Second thing you are doing wrong with your response variable.
you did:
response = [json valueForKey:#"imdbRating"];
User * userObj = [[User alloc]init];
userObj.movieRating = [json valueForKey:#"imdbRating"];
[response addObject:userObj];
here response variable is not an array even though you allocated it as NSMutableArray earlier. As you assign new value in response in the line: response = [json valueForKey:#"imdbRating"];
your variable type will be either NSNumber or NSString based on the type of [json valueForKey:#"imdbRating"].
So remove the line response = [json valueForKey:#"imdbRating"]; and it will work.
By doing this you will hv an array of User objects containing imdbRatings.
UPDATE
According to your comment your code has:
-(void)getIMDBMovie_Rating:(NSMutableArray*)retrievedData {
if (retrievedData.count > 0)
{
userObj = [retrievedData objectAtIndex:0];
NSLog(#"%#is the value",retrievedData);
iMDB_MovieRatingLabel.text=userObj.movieRating;
}
}
Problem is in your getIMDBMovie_Rating. as your method is accepting NSMutableArray as parameter. But when you supply value for your method is NSDictionay [delegate getIMDBMovie_Rating:response]; (you can check by NSLog(#"%#", [response class]);).
So in your getIMDBMovie_Rating method you are accessing [retrievedData objectAtIndex:0];. objectAtIndex is not available with NSDictionay that's why your app get crash.
Try like this,
-(void)parseData:(NSData *)data
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"responseString %#",responseString);
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:(kNilOptions) error:&error];
NSLog(#"json data == %#", json);
NSMutableArray *response =[[NSMutableArray alloc]init];
NSArray *aArray = [json valueForKey:#"imbdRating"];
for (NSDictionary *dictionary in aArray)
{
/* Create a initWithData method in your User Model class and pass the dictionary object to it like,
- (id) initWithData:(NSDictionary *) jsonDictionary
{
self=[super init];
if(self)
{
self.movieRating =[json valueForKey:#"imdbRating"];
} */
User * userObj = [[User alloc]initWithData:dictionary];
[response addObject:userObj];
}
[delegate getIMDBMovie_Rating:response];
}
I am trying to parse JSON without keys.
It looks like this one:
{
"somestring": [
"otherstring1",
float],
"somestring2": [
"somestring3",
float],
"full":integer
}
How I am suppose to parse the first value for each object?
So, when you parse that, you will have a NSDictionary with for which the first two keys have a value which is an NSArray:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
NSLog(#"JSONObjectWithData error: %#", error);
NSArray *array = dictionary[#"22398f2"];
NSString *firstArrayItem = array[0]; // #"CBW32"
NSString *secondArrayItem = array[1]; // #50.1083
Or, if you want all of the first items, you could do something like:
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error)
NSLog(#"JSONObjectWithData error: %#", error);
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *array = obj;
if ([obj isKindOfClass:[NSArray class]])
NSLog(#"first item = %#", array[0]);
else
NSLog(#"The value associated with key '%#' is not array", key);
}];
I am doing a native objC app. ios5
I want to parse a JSON file in the local bundle.
And read each item individually.
To follow is a sample of my JSON file, followed by the code I have working.
I also have explanation of what I think is going on, and the sample code that I need to get assistance with. You are welcome to correct my interpretation as well.
=========================================================================
{"a":[
{"b":{"Q01":"A01","Q02":"B01","Q03":"C01","Q04":"D01","Q05":"E01","Q06":"X","C1":"NR","CABG":"NR","PCI":"NR"}},
{"b":{"Q01":"A01","Q02":"B01","Q03":"C01","Q04":"D01","Q05":"E02","Q06":"X","C1":"I","C1IND":"20","C1SCORE":"3","CABG":"NR","PCI":"NR"}},
{"b":{"Q01":"A01","Q02":"B01","Q03":"C01","Q04":"D01","Q05":"E03","Q06":"X","C1":"NR","CABG":"NR","PCI":"NR"}},
{"b":{"Q01":"A01","Q02":"B01","Q03":"C01","Q04":"D01","Q05":"E04","Q06":"X","C1":"NR","CABG":"NR","PCI":"NR"}},
{"b":{"Q01":"A01","Q02":"B01","Q03":"C01","Q04":"D01","Q05":"E05","Q06":"X","C1":"NR","CABG":"NR","PCI":"NR"}}
]}
My code looks like:
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"nonacs" ofType:#"json"];
NSError* error = nil;
NSData *jsonData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
if (jsonData) {
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(#"error is %#", [error localizedDescription]);
// Handle Error and return
return;
}
//NSArray *keys = [jsonObjects allKeys];
// not necessary becuase I know the Root key is a single "a"
NSString* jsonString = [NSString stringWithFormat:#"%#",[jsonObjects objectForKey:#"a"]];
tLabel01.text = [NSString stringWithFormat:#"jsonData Length is = %d", [jsonData length]];
NSDictionary* dict01 = [[NSDictionary alloc] initWithDictionary:jsonObjects];
l2.text = [NSString stringWithFormat:#"dict01 length = %d", dict01.count];
NSDictionary* dict02 =[[NSDictionary alloc] initWithDictionary:dict01];
l3.text = [NSString stringWithFormat:#"dict2.length = %d", dict02.count];
//NSArray* array01 = [[NSArray alloc] initWithObjects:dict01, nil];
//NSArray *allvalues = [jsonObjects allValues];
//NSArray *allvalues = [[jsonObjects initWithContentsOf ] allValues];
//l3.text = [NSString stringWithFormat:#"allvalues.count = %d", allvalues.count];
//NSDictionary *dictB = [dict01 objectForKey:#"b"];
//l3.text = [NSString stringWithFormat:#"dictB.count = %d", dictB.count];
l3.text = [NSString stringWithFormat:#"jsonObject count = %d", [[jsonObjects objectForKey:#"a"] count]];
// this works really well... except it returned 1700, and there should only be 1550
//l4.text = #"nada";
//[[jsonObjects objectForKey:#"a"] count]]
NSArray *array = [jsonObjects objectForKey:#"a"];
NSArray *arrayVariable = [array objectAtIndex:0];
//l4.text = [NSString stringWithFormat:#"Q01 = %#", [arrayVariable objectForKey: #"Q01"]];
//l4.text =[NSString stringWithFormat:#"arrayVariable count = %d", arrayVariable.count];
NSArray *arrayb = [jsonObjects objectForKey:#"b"];
l4.text = [NSString stringWithFormat:#"arrayb count = %d", arrayb.count];
bTV01.text = jsonString;
};
=============================================================================
The root Object is an NSDictionary with single Key "a".
The value corresponding to that value is an NSArray.
The array contains NSDictionaries with a single Key "b".
The B NSDictionaries contain another NSDictionary.
could someone show me the code to display the 3rd B NSDictionary value for "Q02" please
thanks
[[[root objectForKey:#"a"] valueForKey:#"b"] objectAtIndex:2]
So i have this JSON:
{"Curs":[{"ID":"AED","Name":"Dirhamul Emiratelor Arabe","Curs":"0.8013","Multiplier":"1","Data":"2011-03-21"},{"ID":"AUD","Name":"Dolarul australian","Curs":"2.9611","Multiplier":"1","Data":"2011-03-21"},{"ID":"BGN","Name":"Leva bulgareasc","Curs":"2.1314","Multiplier":"1","Data":"2011-03-21"},{"ID":"BRL","Name":"Realul brazilian","Curs":"1.7636","Multiplier":"1","Data":"2011-03-21"},{"ID":"CAD","Name":"Dolarul canadian","Curs":"3.0137","Multiplier":"1","Data":"2011-03-21"},{"ID":"CHF","Name":"Francul elvetian","Curs":"3.2484","Multiplier":"1","Data":"2011-03-21"},{"ID":"CNY","Name":"Renminbi-ul chinezesc","Curs":"0.4483","Multiplier":"1","Data":"2011-03-21"},{"ID":"CZK","Name":"Coroana ceha","Curs":"0.1707","Multiplier":"1","Data":"2011-03-21"},{"ID":"DKK","Name":"Coroana daneza","Curs":"0.559","Multiplier":"1","Data":"2011-03-21"},{"ID":"EGP","Name":"Lira egipteana","Curs":"0.4959","Multiplier":"1","Data":"2011-03-21"},{"ID":"EUR","Name":"Euro","Curs":"4.1685","Multiplier":"1","Data":"2011-03-21"},{"ID":"GBP","Name":"Lira sterlina","Curs":"4.7864","Multiplier":"1","Data":"2011-03-21"},{"ID":"HUF","Name":"100 Forinti maghiari","Curs":"1.5354","Multiplier":"100","Data":"2011-03-21"},{"ID":"INR","Name":"Rupia indiana","Curs":"0.0653","Multiplier":"1","Data":"2011-03-21"},{"ID":"JPY","Name":"100 Yeni japonezi","Curs":"3.6213","Multiplier":"100","Data":"2011-03-21"},{"ID":"KRW","Name":"100 Woni sud-coreeni","Curs":"0.2623","Multiplier":"100","Data":"2011-03-21"},{"ID":"MDL","Name":"Leul moldovenesc","Curs":"0.2507","Multiplier":"1","Data":"2011-03-21"},{"ID":"MXN","Name":"Peso-ul mexican\t","Curs":"0.2452","Multiplier":"1","Data":"2011-03-21"},{"ID":"NOK","Name":"Coroana norvegiana","Curs":"0.5286","Multiplier":"1","Data":"2011-03-21"},{"ID":"NZD","Name":"Dolarul neo-zeelandez","Curs":"2.164","Multiplier":"1","Data":"2011-03-21"},{"ID":"PLN","Name":"Zlotul polonez","Curs":"1.0299","Multiplier":"1","Data":"2011-03-21"},{"ID":"RSD","Name":null,"Curs":"0.0404","Multiplier":"1","Data":"2011-03-21"},{"ID":"RUB","Name":"Rubla ruseasca","Curs":"0.1039","Multiplier":"1","Data":"2011-03-21"},{"ID":"SEK","Name":"Coroana suedeza","Curs":"0.4697","Multiplier":"1","Data":"2011-03-21"},{"ID":"TRY","Name":"Lira turceasca","Curs":"1.8665","Multiplier":"1","Data":"2011-03-21"},{"ID":"UAH","Name":"Hryvna ucraineana","Curs":"0.3699","Multiplier":"1","Data":"2011-03-21"},{"ID":"USD","Name":"Dolarul american","Curs":"2.9428","Multiplier":"1","Data":"2011-03-21"},{"ID":"XAU","Name":"Gramul de aur","Curs":"135.0844","Multiplier":"1","Data":"2011-03-21"},{"ID":"XDR","Name":"DST","Curs":"4.678","Multiplier":"1","Data":"2011-03-21"},{"ID":"ZAR","Name":"Randul sud-african ","Curs":"0.4233","Multiplier":"1","Data":"2011-03-21"}]}
And i want to parse it but i am new to this and don't know how. For example how could i get the values from ID.
Here is my code:
#import "DownloadData.h"
#import "JSON.h"
#implementation DownloadData
-(void) connection
{
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://source"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSLog(json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
//NSLog([json_string description]);
//NSLog([json_string objectForKey:#"Curs"]);
/*
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#",[status objectForKey:#"Curs"]);
}
*/
NSLog(#"test");
//jsondownload=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
#end
Do:
NSDictionary *responseObj = [parser objectWithString:json_string error:nil];
NSArray *statuses = [responseObj objectForKey:#"Curs"];
for (id anUpdate in statuses) {
NSLog(#"ID: %#", [(NSDictionary*)anUpdate objectForKey:#"ID"]);
}