Converting a JSON string into NSDictionary [closed] - objective-c

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];

Related

I'm new to this coding language, Json parsing troubleshooting [closed]

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];

Objective C - how to Json Parse a dictionary having many dictionaries inside it?

Here is the main dictionary - 'query'.
I want to access 'results'- It is a NSDictionary having some key - pair values.
But, all the elements of 'query' dictionary (i.e count, results, created, lang, diagnostics) are inside 'query' dictionary's 0th element.
This is what I have written to access 'results'.
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"restuarant" ofType:#"json"]];
//query is main NSDictionary
self.query = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//results is an NSDictionary
self.results = [_query valueForKey:#"results"][0];
But, when I debug it, everything is getting saved in 'query' variable but nothing is getting stored in 'results' variable.
I also tried the following code, but that didn't work out as well -
self.results = [_query valueForKey:#"results"];
I have looked upon many other stackoverflow pages, but none of them suit my needs. Regards.
From what I understand, it should be something like:
//results is an NSDictionary
self.results = [[_query valueForKey:#"query"] valueForKey:#"results"];
To debug it easier and to understand better the structure, you can also break the access to the results dictionary, into multiple steps, like:
NSDictionary *queryDictionary = [_query valueForKey:#"query"];
self.results = [queryDictionary valueForKey:#"results"];
then you can check what you have in the first dictionary and then in the second one.
Hope this helps!

Convert Unicode \u009e to acute accent from JSON

I am using Xcode in objective-C and I try to figure out how I could convert "\U009e" character to "é" but I am still stuck despite a lot of discussions about this topic.
Basically, I have created inside my Xcode project a JSON file that looks like this:
{
"ééé":["1"],
}
When I get the file by the NSJSONSerialization method:
NSString *dataPath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"json"];
id jsonObject = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath] options:kNilOptions error:&error];
I end up with unicode characters (like \U009e) instead of an acute accent. I know I need to find a way to convert/decode/... during the process but I don't know how to do it.
Would anyone have an idea?

How to save apps data Xcode

I have been searching for many days on how to save my apps data. I found some stuff but it was very complicated and badly explained. I need that when I completely close my apps all the data I entered in the text field are still there when I open my apps again. I tried a tutorial but this only let me save about 8 textfields and I need to save thousands I am starting Objective-C and Xcode so if somebody want to give me an answer please make it very precise.
Alright, what I'd suggest would be putting all the data from your text fields into an array and saving that to a file, then loading it when you re-open the app.
The first thing you need is a save file. This function will create one for you.
-(NSString*) saveFilePath{
NSString* path = [NSString stringWithFormat:#"%#%#",
[[NSBundle mainBundle] resourcePath],
#"myfilename.plist"];
return path;}
Now that that's done you need to create your saving array. Hopefully you have your thousands of textfields already fitted into an array of some sort. If not, this will be a painful process regardless of how you tackle it. But anyway... (Here, labelArray will be the array of all your text fields/labels/etc.)
NSMutableArray* myArray = [[NSMutableArray alloc]init];
int i = 0;
while(i < labelArray.count){
[myArray addObject: [labelArray objectAtIndex: i].text];
i ++;
}
[myArray writeToFile:[self saveFilePath] atomically:YES];
[myArray release];
And the loading code would be something along the lines of
NSMutableArray* myArray = [[NSMutableArray arrayWithContentsOfFile:[self saveFilePath]]retain];
Then you'd simply load the data back into your array of text fields.
Hope this helps.
It sounds like your application architecture may be unsound if you are planning on saving thousands of text fields' data in the fraction of a second you get while your app is closing. It would probably be better to save these as the user enters the data instead of waiting to save all the data at once.
To get the path you are going to write ( or read from! ) to, you do the following:
NSString *writableDBPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:#"MyFile.extension"];
And then use a method like "writeToFile:automically:" of NSString or NSDictionary etc. to write to the path.

parsing JSON using objective C?

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.