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?
Related
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];
I get the html source of a page to a NSString like this
NSString* url = #"example url";
NSURL *urlRequest = [NSURL URLWithString:url];
NSError *err = nil;
NSString *response = [NSString stringWithContentsOfURL:urlRequest encoding:kCFStringEncodingUTF8 error:&err];
a part of the response is like : 2 \u00cf\u0083\u00cf\u0087\u00cf\u008c\u00ce\u00bb\u00ce\u00b9\u00ce\u00b1
How can i have the Greek characters shown as they should in the NSString response?
The encoding of the page is "charset=iso-8859-7"
Ahhh, I understand your question a little bit better now.
The Apple-supplied native implementation of NSString doesn't know what to do with iso-8859-7 encoding.
You have two options.
1)
Try requesting different encodings to [NSString stringWithContentsOfURL: encoding: error:] to see if one successfully loads. My first attempt would be with NSISOLatin1StringEncoding.
2)
I found a third party library (and NSString category extension) that does do iso-8859-7 conversion. But to get access to CkoCharset will cost you (or your client) $290 USD. It might be a worthwhile investment to save time & hassle.
https://chilkatsoft.com/charset-objc.asp
and documentation is here:
http://www.chilkatsoft.com/refdoc/objcCkoCharsetRef.html
I am trying to get HTML files from the web, using stringWithContentsOfURL:. My problem is, sometimes it works but sometimes it doesn't. For example, I tried:
NSString *string = [NSString stringWithContentsOfURL:
[NSURL URLWithString:#"http://www.google.com/"]
encoding:encoding1
error:nil];
NSLog(#"html = %#",string);
This works fine, but when I replace the URL with #"http://www.youtube.com/" then I only get "NULL". Is there anyone that knows what's going on? Is it because of YouTube having some sort of protection?
Google's home page uses ISO-8859-1 encoding (aka "Latin-1", or NSISOLatin1StringEncoding). YouTube uses UTF-8 (NSUTF8StringEncoding), and the encoding you've specified with your encoding1 variable has to match the web page in question.
If you just want the web page and don't really care what encoding it's in, try this:
NSStringEncoding encoding;
NSError *error;
NSString *string = [NSString stringWithContentsOfURL:
[NSURL URLWithString:#"http://www.google.com/"]
usedEncoding:&encoding
error:&error];
NSLog(#"html = %#",string);
This method will tell you what the encoding was (by writing it to the encoding variable), but you can just throw that away and focus on the string.
I'm trying to display some japanese text on the ios simulator and an ipod touch. The text is read from an XML file. The header is:
<?xml version="1.0" encoding="utf-8"?>
When the text is in english, it displays fine. However, when the text is Japanese, it comes out as an unintelligible mishmash of single-byte characters.
I have tried saving the file specifically as unicode using TextEdit. I'm using NSXMLParser to parse the data. Any ideas would be much appreciated.
Here is the parsing code
// Override point for customization after application launch.
NSString *xmlFilePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"questionsutf8.xml"];
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath];
NSData *data = [NSData dataWithBytes:[xmlFileContents UTF8String] length:[xmlFileContents lengthOfBytesUsingEncoding: NSUTF8StringEncoding]];
XMLReader *xmlReader = [[XMLReader alloc] init];
[xmlReader parseXMLData: data];
stringWithContentsOfFile: is a deprecated method. It does not do encoding detection unless the file contains the appropriate byte order mark, otherwise it interprets the file as the default C string encoding (the encoding returned by the +defaultCStringEncoding method). Instead, you should use the non-deprecated [and encoding-detecting] method stringWithContentsOfFile:usedEncoding:error:.
You can use it like this:
NSStringEncoding enc;
NSError *error;
NSString *xmlFileContents = [NSString stringWithContentsOfFile:xmlFilePath
usedEncoding:&enc
error:&error];
if (xmlFileContents == nil)
{
NSLog (#"%#", error);
return;
}
First, you should verify with TextWrangler (free from the Mac app store or barebones.com) that your XML file truly is UTF-8 encoded.
Second, try creating xmlFileContents with +stringWithContentsOfFile:encoding:error:, explicitly specifying UTF-8 encoding. Or, even better, bypass the intermediate string entirely, and create data with +dataWithContentsOfFile:.
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.