Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have followed some courses and got to a stage where I nearly have what I want. I'll add the section of code below with the error that needs fixing. Its probably really easy to fix its just that I'm new to this and I have no idea what I'm doing.
error: Expected method to read dictionary element not found on object of type 'NSMutableArray *'
This probably isn't the most efficient way of doing this and don't use any over complicated words or phrases to help cut ima not understand them. If anyone could just fix the code that'll be really useful. and thank you.
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"https://******/latest.json"];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"json: %#", json);
NSString *BGmmol = json[#"mmol"];
You need to store the parsing result in a dictionary:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions];
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have a dictionary that sometimes reads a null value from some JSON data. When I do :
NSDictionary *caption=[image objectForKey:#"caption"]; //crash here!
Where the field caption is there but null, (in the JSON, caption:null), I get a crash.
How can I eliminate this?
I can check for null later on with:
NSDictionary *caption=[image objectForKey:#"caption"];
NSString *text=#"";
if( caption!=NULL )
{text=[caption objectForKey:#"text"]; }
but the crash comes even before this.
This is how my dictionary is being built:
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *myResults=[result objectForKey:#"data"];
long count=[myResults count];
for(NSDictionary *image in myResults)
{
NSDictionary *links=[image objectForKey:#"images"];
NSDictionary *standard=[links objectForKey:#"standard"];
NSString *url=[standard objectForKey:#"url"];
NSLog(#"image:%#",image);
NSDictionary *caption=[image objectForKey:#"caption"]; //CRASH
Are you sure that NSDictionary *caption=[image objectForKey:#"caption"]; would return a dictionary?
Anyway, the way to check to see if it's JSON null is:
if ([image[#"caption"] isEqual:[NSNull null]]) { // it's null }
Note that dictionaries and arrays can't contain nil. nil isn't an object value. [NSNull null] is a special object that is the equivalent of nil and can be used in places where nil can't.
https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSNull_Class/Reference/Reference.html
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm trying to build an app in which people can order goods from different stores. I am totally new to programming, and I thought building a project like this would be a good way to learn it.
I'm stuck at the part of my app where a user can search for a company (on company name, location, or both) in my database. The database returns a JSON string, containing the company name and location for all found companies, which looks like this:
{"companyName":"testcompany_1","companyCity":"Tiel"},
{"companyName":"tectcompany_2","companyCity":"Tiel"}
So far so good!
now I want to turn this JSON string, which is an NSString, into an NSDictionary, in order to display the names and locations of the found companies in a tableView. This is where I get stuck.
I have been searching through StackOverflow, google, etcetera, and I have tried several ways to do this, for example:
Convert NSString to NSDictionary separated by specific character
Convert JSON feed to NSDictionary
Since none of the tutorials/answers is saw really solves my problem, I tried to make something out of them myself, and this is the result of that:
NSString *strURL = [NSString stringWithFormat:#"http://www.imagine-app.nl/companySearch.php?companyNameSearchField=%#&companyCitySearchField=%#", companyNameSearchField.text, companyCitySearchField.text];
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSArray *companies = [inputString componentsSeparatedByString:#"},{"];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:companies] options:kNilOptions error:nil];
To me, this makes sense. First, turn an NSString into an NSArray to separate objects, and after that convert the string into an NSDictionary, which can be used by the tableview I want to populate with this.
But when I log the dictionary, it says null, so no NSDictionary seems to be made by this code.
Now after several weeks of trying and searching, i'm starting to feel pretty stupid and desperate because I cannot find a good way to do this.
Does anyone know bow to turn a json string as shown above, into an NSDictionary?
What you want to do is the following:
NSURL *anURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://www.imagine-app.nl/companySearch.php?companyNameSearchField=%#&companyCitySearchField=%#", companyNameSearchField.text, companyCitySearchField.text]];
NSData *jsonData = [NSData dataWithContentsOfURL:anURL];
NSArray *mainArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:NULL];
// In mainArray are NSDictionaries
for (NSDictionary *informationOnOneCompany in mainArray) {
NSString *name = informationOnOneCompany[#"companyName"];
NSString *city = informationOnOneCompany[#"companyCity"];
// Now you can store these two strings in that array or whatever populates your tableview ;)
}
Lets have a look at the steps:
We create an NSURL instance with the link we want.
We download the contents of that link into an NSData object.
We know how the JSON we receive looks like and identify that the "top layer" is an array. So we create an NSArray and initialize it with the JSON we received.
The curly braces and the colons in the JSON you posted tell us that in that array we created are instances of NSDictionary.
We loop through the NSArray using fast enumeration.
In every NSDictionary we look at the keys "companyName" and "companyCity" and store their values in an NSString.
Not implemented in the code above: You can populate your NSArray which is the datasource of your tableView
Hope that helps, if you have questions let me know ;)
No, it doesn't make sense at all, at several places. For example:
[NSData dataWithContentsOfFile:companies]
Huh, what? companies is an NSArray containing NSStrings - it's not a file path which points to a file you could initialize the data object with.
(It seems you're making assumptions about what the individual methods do - why that? It would be better to read the documentation - you wouldn't waste your and our time.)
The text/data you presented in the question is also not valid JSON. The only thing I can imagine is that the web service does indeed return valid JSON, i. e. the comma-separated dictionaries are correctly wrapped between [ ] to form an array, you just forgot to include them. In this case, you don't have to rape the string and poor Foundation framework, just convert the JSON to an array and it will be fine:
NSURL *url = [NSURL URLWithString:#"http://example.com/foo.json"];
NSData *data = [NSData dataWithContentsofURL:url];
NSArray *response = [NSJSONSerialization jsonObjectWithData:data options:kNilOptions error:NULL];
Is there a way with NSJSONSerialization to check that the NSData is valid JSON? I don't want the application to error out if the API returns invalid JSON for some reason.
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
This won't "error out", it'll just return nil if the JSON isn't valid. Thus the test to see if it is valid JSON would be:
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Handle error
}
If it does return nil then you can check error to see what went wrong.
NSJSONSerialization Class have a method to do exactly this... (EDIT: no it doesn't...)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
BOOL isValid = [NSJSONSerialization isValidJSONObject:jsonObj];
EDIT: (After hypercrypts' comment)
Hypercrypt is right (I really can't understand how I missed that)...
Even though my answer seems to be working, it's wrong.
What isValidJSONObject: method does is to check if an object can be serialized into JSON and not the other way round. So his answer is what you're looking for. You could use though this method in the case you grab a mutable copy from a json payload, mutate it and later want to check if it's safe to try and re-serialize it back to a JSON string. But bottom line is that hypercrypt's answer is the correct one and I think that it would be more than fair to mark his answer as correct instead of mine. Anyway, sorry about any confusion and #hypercrypt thank's for pointing that out :)
There isn't really a way to check the data without creating the object with NSJSONSerialization; I would put it in a try-catch. If you end up in the catch block, it's not valid JSON.
EDIT: Come to think of it, if it encountered an error, 'error' is an error object. So even if nothing is thrown you can check that to see if the data was valid.
I am trying to use NSJSONSerialization to serialize the data returned from stack overflow API, but it is not working as intended :(
I am using code as below :
NSURL *apiURL = [NSURL URLWithString:#"http://api.stackoverflow.com/1.1/questions?tagged=objective-c&pagesize=30"];
NSError *error = nil;
// First option - failed
NSInputStream *inputStream = [NSInputStream inputStreamWithURL:apiURL]; // returning nil
id jsonFound1 = [NSJSONSerialization JSONObjectWithStream:inputStream options:NSJSONReadingMutableContainers error:&error];
// Second option - failed
NSData *jsonData = [NSData dataWithContentsOfURL:apiURL]; // returning correct value, verified after converting it to NSString
id jsonFound2 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; // returning nil
I am trying the above code in Xcode 4.2 for iOS5 and I am getting (null) for inputStream and for jsonFound2.
Earlier I was doing it through SBJSON and it was working correctly.
Can anyone suggest me if I am doing anything wrong or missing anything?
I think there may be a missing step after assigning an inputStream.
[inputStream open];
I have not tried this with remote URLs, but have seen examples that use this approach.
First option does not work because it supports only file url (thanks to David for pointing).
Second option works fine for remote urls.
I have spent 1 week studying objective C. Now I am quite confused at the dealing with data part.
My friend gave me a link
http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2
and ask me write a class to parse this JSON. I had no clue what parsing JSON means. but I have gone online and looked up. I could understand a basics of it and then I impletemented a punch of code to parse this JSON. Which is:
-
(void)parseURL
{
//create new SBJSON object
SBJSON *parser = [[SBJSON alloc] init];
NSError *error = nil;
//perform request from URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
NSDictionary *results = [parser objectWithString:json_string error:&error];
// array just for the "answer" results
NSArray *quizes = [results objectForKey:#"quiz"];
NSDictionary *firstQuiz = [quizes objectAtIndex:0];
// finally, the name key
NSString *extract = [firstQuiz objectForKey:#"extract"];
NSLog(#"this is: %#", [extract valueForKey:#"extract"]);
}
This is at the implementation file, but in the header file I could not declare any variables, it will print out some errors. I tried to run this, there is no errors, but I am not sure this code is correct or not. And my friend asked me to write a class into an existing project. I don't know what needs to be modified and what not. I am so blur right now. Could anyone pro in this give me a hand. ?
My sincere thanks.
Thanks for reply. I have downloading and added the JSON framework ealier too. I am just not sure where to begin and where to end, meaning the step I should do when I add JSON framework into it. I could understand the syntax but I am not sure about the steps I should do. I am a newbie in this.
If you support iOS 5.0+, you should use built-in NSJSONSerialization.
It is faster than TouchJSON.
You could just use TouchJSON: http://code.google.com/p/touchcode/wiki/TouchJSON
Or you could use this one: http://code.google.com/p/json-framework/
I'm sure there are others. I use TouchJSON... it's fast and has a good API.
I recommend working through Ray Wenderlich's MapKit tutorial, especially if you are a newbie. It covers several common iOS development issues, including parsing JSON data.
http://www.raywenderlich.com/2847/introduction-to-mapkit-on-ios-tutorial
"The Implementation" section is where his JSON feed is retrieved and then in "Plotting the Data" he uses the SBJson library to parse it.