Xcode - Special characters in JSON - ios

Im loading a database from a website through JSON. When I download the database I use UTF8 to make all characters appear correctly and when I NSLOG them it all appears as it should. But when I analyze the data using JSON and afterwards try to filter out just a few of the words, the words with special characters become like this: "H\U00f6ghastighetst\U00e5g" where it should say: "Höghastighetståg".
I have tried to find a way to make the code convert the text back to UTF8 after filtering but somehow I can't make it happen. Would be really helpful for some answers.
NSError *error;
NSString *url1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.pumba.se/example.json"] encoding:NSUTF8StringEncoding error:&error];
NSLog(#"Before converting to NSData: %#", url1);
NSData *allCoursesData = [url1 dataUsingEncoding:NSUTF8StringEncoding];
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(#"%#", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:#"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[#"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[#"properties"];
NSString *status = [properties[#"Status"] firstObject];
NSString *name = [properties[#"Name"] firstObject];
if ([status isEqualToString:#"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(#"All names: %#", allNames);
}}

try with
+ (NSString *)utf8StringEncoding:(NSString *)message
{
NSString *uniText = [NSString stringWithUTF8String:[message UTF8String]];
NSData *msgData = [uniText dataUsingEncoding:NSNonLossyASCIIStringEncoding];
message = [[NSString alloc] initWithData:msgData encoding:NSUTF8StringEncoding];
return message;
}
or
+ (NSString *)asciiStringEncoding:(NSString *)message
{
const char *jsonString = [message UTF8String];
NSData *jsonData = [NSData dataWithBytes:jsonString length:strlen(jsonString)];
message = [[NSString alloc] initWithData:jsonData encoding:NSNonLossyASCIIStringEncoding];
return message;
}
and this code can help you
+ (NSDictionary *)jsonStringToObject:(NSString *)jsonString
{
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse;
if (data)
jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return jsonResponse;
}
+ (NSString *)objectToJsonString:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
if (jsonData.length > 0 && !error)
{
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
return nil;
}

Related

Create JSON format using NSString as a key and values

I have JSON format requirement something like this.
{
"first_name" : "XYZ",
"last_name" : "ABC"
}
I have values in NSString.
NSString strFName = #"XYZ";
NSString strLName = #"ABC";
NSString strKeyFN = #"first_name";
NSString strKeyLN = #"last_name";
And I use NSMutableDictionary
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
then output is
{
first_name = XYZ,
last_name = ABC
}
So I don't want "=" separating key & values instead I want ":" to separate key and values
I have went most of the stack overflow questions but didn't help getting "=" only in output
So please any help ?
Here is your answer :
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSInteger number = 15;
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSString *numValue = #"Number";
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:strFName forKey:strKeyFN];
[dic setObject:strLName forKey:strKeyLN];
[dic setObject:[NSNumber numberWithInt:number] forKey:numValue];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dic] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON %#",jsonString);
You write this code after your NSDictionary
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonstr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSDictionary *ictionary = [NSDictionary dictionaryWithObjectsAndKeys:
strKeyFN, strFName,strKeyLN, strLName,nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary as string:%#", jsonString);
NSString *strFName = #"ABC";
NSString *strLName = #"XYZ";
NSString *strKeyFN = #"last_name";
NSString *strKeyLN = #"first_name";
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[NSArray arrayWithObject:dict] options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStrng = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"Your required JSON is %#",jsonStrng);
try this:-
NSString *cleanedString1 =[strFName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSString *cleanedString2 =[strLName stringByReplacingOccurrencesOfString:#"/"" withString:#""];
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:
cleanedString1, strKeyFN,
cleanedString2, strKeyLN,nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:Dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
this very robust code to achieve you goal
NSDictionary *userDic = #{strKeyFN:strFName,strKeyLN:strLName};
you have to convert NSMutableDictionary into NSData
then convert the NSData Into json string you want
NSString *strFName = #"XYZ";
NSString *strLName = #"ABC";
NSString *strKeyFN = #"first_name";
NSString *strKeyLN = #"last_name";
NSMutableDictionary* dict = [[NSMutableDictionary alloc]init];
[dict setObject:strFName forKey:strKeyFN];
[dict setObject:strLName forKey:strKeyLN];
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jasonString= [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

Cannot encode the data in ios

Cannot encode the data in ios which fetch from webservice.
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSMutableArray *parts = [[NSMutableArray alloc] init];
for (NSString *key in dictionary) {
NSString *encodedValue = [[NSString stringWithFormat:#"%#",[dictionary objectForKey:key]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *encodedKey = [[NSString stringWithFormat:#"%#",key] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *part = [NSString stringWithFormat: #"%#=%#", encodedKey, encodedValue];
[parts addObject:part];
}
NSString *encodedDictionary = [parts componentsJoinedByString:#"&"];
return [encodedDictionary dataUsingEncoding:NSUTF8StringEncoding];
}
It seems you are encoding NSDictionary and generate a NSString. And again Encoding that NSString and returns it.
You may do it in easy way as below.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
You may return above jsonData in your function to achieve your requirement as below.
- (NSData*)encodeDictionary:(NSDictionary*)dictionary {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
return jsonData;
}
}

iOS - How to properly read JSON file with umlauts

I am having difficulties converting a JSON file into an NSDictionary without losing umlauts.
{
"België": "5",
"Haïti": "45"
}
This is a short version of the contents of a .json file in my supporting files in Xcode.
I need to convert them to an NSDictionary without losing those umlauts.
NSString *file =[[NSBundle mainBundle] pathForResource:#"countries_and_rates" ofType:#"json"];
NSString *cr = [NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:NULL];
After that, I give cr to this method:
+ (NSDictionary*)jsonFromData:(NSData*)data {
if([self isEmpty:data] || ![data isKindOfClass:[NSData class]])
return nil;
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if(!str)
return nil;
NSError* error;
id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if(error)
NSLog(#"************** Error: jsonFromData: %#/%#", error.localizedDescription, error);
if([json isKindOfClass:[NSDictionary class]])
return json;
else if([json isKindOfClass:[NSArray class]])
return [NSDictionary dictionaryWithObject:json forKey:#"results"];
return #{};
}
If someone could help me and tell me what I am doing wrong.
FYI: tried all kinds of encoding, such as NSISO and NSUTF
Don't mess around with encodings, let the framework figure it out for you:
NSData *data = [NSData dataWithContentsOfFile:filepath];
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

Getting error when parsing JSON iOS

After get string from web service, i need to parse them. But something is going wrong.
Here is my code;
NSString *responseString = [request responseString];
NSLog(#"response String = %#",responseString);
NSData *tempData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSString *innerJson = [NSJSONSerialization JSONObjectWithData:tempData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"innerJson = %#",innerJson);
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
NSLog(#"entries = %#",entries);
for (NSDictionary *entry in entries) {
NSLog(#"entry = %#",entry);
NSString *message = [entry objectForKey:#"message"];
NSLog(#"message = %#",message );
NSString* result = [entry objectForKey:#"result"];
NSLog(#"result = %#", result);
}
Here is my output;
innerJson = {"result": false,"message":"message!"}//I need parse this string.
entries = {
message = "message!";
result = 0;
}
entry = message
I am taking error in for loop.
What am i doing wrong?
Thanks for interest and advice.
The problem is that in the line
NSArray *entries = [NSJSONSerialization
you assign the result to NSArray, and your JSON object is a dictionary, so you should assign to NSDictionary. Then the for loop is unnecessary - you can do:
NSDictionary *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
NSLog(#"entries = %#",entries);
NSString *message = [entries objectForKey:#"message"];
NSLog(#"message = %#",message );
NSString* result = [entries objectForKey:#"result"];
NSLog(#"result = %#", result);
Read more details in NSJSONSerialization documentation.
I'm not sure - but I guess this code should work for you:
NSString *responseString = [request responseString];
NSLog(#"response String = %#",responseString);
NSData *tempData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
/* assuming it is a dictionary */
NSDictionary *inner = [NSJSONSerialization JSONObjectWithData:tempData
options:NSJSONReadingAllowFragments error:&error];
NSLog(#"inner = %#",inner);
for(id key in inner) {
id value = [inner objectForKey:key];
NSLog(#"key=%#, value=%#", key, value);
}

Unrecognized selector sent to instance in JSON parsing

Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.

Resources