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);
}];
Related
I currently have the code below to decode some received JSON data. However, since Feedly doesn't give any indexes back I don't know how to properly decode the JSON data. This is an example of JSON I receive back:
[
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
},
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/design",
"label": "design"
}
]
And if I let the code below run, the NSLog outputs it perfectly. But how do I fetch the label variables from res?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of notifications",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
NSLog(#"res value contains: %#", res);
}
If short to get label values use [res valueForKeyPath:#"label"];
But to make it work in right way you need to change type of res to NSArray because provided JSON contains array of dictionary.
Then you can traverse through with for-in.
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
for (NSDictionary *d in res) {
NSLog(#"label %#",[d objectForKey:#"label"]);
}
NSLog(#"res value contains: %#", res);
I Have got this Response from WebService
{"d":"{"token":"b502645e-837f-4237-a6ff-d4323f2799dd","timestamp":"09/11/20147:46:43PM"}"}
I want to Parse this String so that i can get output like :
token = b502645e-837f-4237-a6ff-d4323f2799dd
timestamp = 09/11/20147:46:43PM
So that i can Store it into Database.
This is my Code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
/*
NSError *errorJson=nil;
NSString* OuterDict = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&errorJson];
NSLog(#"Outer Dictionary %#",OuterDict);
*/
NSString *responseData = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
responseData = [responseData stringByReplacingOccurrencesOfString:#" " withString:#""];
responseData = [responseData stringByReplacingOccurrencesOfString:#"\\" withString:#""];
//NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//NSLog(#"%#",encodedString);
NSLog(#"Reponse data %#",responseData);
NSError *errorJson=nil;
NSData *jsonData = [responseData dataUsingEncoding:NSUTF8StringEncoding];
jsonData = [jsonData subdataWithRange:NSMakeRange(0, [jsonData length] - 1)];
NSDictionary* OuterDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&errorJson];
NSLog(#"Outer Dict %#",OuterDict);
}
I am getting null as Output:
Outer Dict (null)
Can Anyone Help me With this.
Thanks In Advance.
Use following snippets at the top of your method. it will parse your JSON data and returns dictionary. You can perform any operations on Dictionary according to your need.
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingAllowFragments error:&err];
NSLog(#"Response : %#", dictResponse);
Happy coding :)
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 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]