Parse double quotes and single quotes in Json Parsing - ios

I am parsing a JSON url. I am getting \u00e2\u20ac\u0153 instead of single quotes and \u00e2\u20ac\u009d instead of double quotes. On my end i am doing NSUTF8StringEncoding but still not getting single and double quotes.
Here is the response in the web browser:
{"status":"1","data":[{"id":"1345","title_en":"","content_en":"Mom
said, \u00e2\u20ac\u0153I love this one.\u00e2\u20ac\u009d\n\nJake
said, \u00e2\u20ac\u0153I don\u00e2\u20ac\u2122t get
it.\u00e2\u20ac\u009d\n","image":"1396","pos":"2","video_type":"0","video":"0","video_alt":"","sound_type":"1","sound":"1123","sound_alt":"","author":"","type":"0","book_id":"148","user_id":"24","title":"The
Art
Museum","author_url":"maureen-d-1","book_url":"the-art-museum","video_filename":"","sound_filename":"atmuseum2.m4a"}]}
Is it possible to parse above response using NSUTF8StringEncoding or something else. Or i need to get it done from php side.

Do you use NSJSONSerialization? In my app i do this:
NSError* localError;
id jsonObjects = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&localError];
In "data" variable i have response from server. I receiving UTF-encoded text from server too (like \u00e2\u20ac) but finally i get normal string. "jsonObjects" will contain data in native types:
if ([jsonObjects isKindOfClass:[NSDictionary class]])
{
NSNumber* age = [jsonObjects objectForKey:#"age"];
//...etc
}

Related

Weird sorting when parsing JSON

I am working on an App and I use my JSON RESTful API. Therefor I parse JSON like in the following example:
NSData * apiReturn;
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:NSJSONReadingMutableLeaves error:&myError];
If I now pass the following JSON encoded String via the API to the App:
{"da": {"name":"dienstlicher Anlass", "duty":true, "type":"dropdown",
"values":{"gt":{"name":"Gesprächstermin", "recurring":true,
"values":{"fa":{"name":"Firma", "duty":true, "type":"text",
"multiline":false}, "ar":{"name":"Anrede", "duty":true, "single":true,
"type":"checkbox", "values":{"fr":{"name":"Frau"},
"hr":{"name":"Herr"}}}, "nm":{"name":"Gesprächspartner", "duty":true,
"type":"text", "multiline":false}, "bm":{"name":"Bemerkung",
"duty":false, "type":"text", "multiline":true}}}}
},"bm":{"name":"Bemerkung", "values":[],
"type":"text"},"bm2":{"name":"Bemerkung", "values":[], "type":"text"}}
(You can parse this a bit prettier here: http://json.parser.online.fr)
The NSDictionary should contain the following Keys: "da", "bm", "bm2" - Sorted this way, because this is the sorting of the JSON String!
But what Objective-C does, is this:
Why does Objective-C sort the elements, and why so wrong?
I hope you can help! :)
An NSDictionary is not guaranteed to store the keys in any given order.

AFNetworking sending URL as post parameter

I am calling an API in which I am sending a URL link as a post parameter with it.
But while converting it into JSON data using
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:lParameters options:NSJSONWritingPrettyPrinted error:&error];
it adds extra '\' character into the link.
and when I log that data string, it logs like
data string : {
"id" : "1",
"photoLink" : "https:\/\/7.7.100.120:8443\/webresource\/carsevent\/gallery\/approved\/image-a31ea5e0-6284-402a-9e6a-b0cdba37bc1f.png"
}
Log :
Dictionary :
{
id = 1;
photoLink = "https://7.7.100.120:8443/webresource/carsevent/gallery/approved/image-a31ea5e0-6284-402a-9e6a-b0cdba37bc1f.png";
}
So API is returning error in this case.
How can I overcome from this?
Any help would be much appreciable.
Thanks
JSON must have certain characters escaped with a "\" character and even though "/" is not required to be escaped it is allowed to be escaped. Therefor the JSON with escaped "/" characters is valid and should be accepted by the API.
You can remove them if needed.
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\\/" withString:#"/"];
jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
File a bug report: http://bugreport.apple.com requesting an option to not escape "/".
See this SO answer.
See JSON for the characters that must be escaped.

Converting JSON string into object

I am trying to convert a JSON string into an object in Objective C using the code:
NSString *jsonString = (NSString *) responseObject;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
The value of jsonString is
"[{\"Date\": \"12-01-2015\", \"Time\": \"7:00 am\", \"Title\":
\"First Car Service\", \"Details\": \"This was the first car
service ever done\"}]"
But the value of json is always nil. How do I convert the jsonString into a NSArray ?
My (third) bet: your json string isn't correct. If it contains the leading and trailing quotes strip them. Replaced the \" with ".
better: make the server or other json source send correct json.
From the error, it may be that your string is not formatted correctly, probably due to the quotes.
You should also make sure that after you have formatted the string, then you check the array has objects.
NSLog(#"JSON Details: %#", json[0][#"Details"]);

How to process response from Instapaper API?

I make a request to the Instapaper API, and it's supposed to return JSON. It returns something close to JSON, but not completely, like follows:
2013-05-30 19:54:20.155 --[53078:c07] (
{
type = meta;
},
{
"subscription_is_active" = 1;
type = user;
"user_id" = --;
username = "--#gmail.com";
},
{
"bookmark_id" = 387838931;
description = "";
hash = YHwQuwhW;
"private_source" = "";
progress = 0;
"progress_timestamp" = 0;
starred = 0;
time = 1369954406;
title = "Adobe Finally Releases Kuler Color-Picking App for iPhone - Mac Rumors";
type = bookmark;
url = "http://www.macrumors.com/2013/05/30/adobe-finally-releases-kuler-color-picking-app-for-iphone/";
},
How do I then process this? Can I take it and turn it into an NSDictionary even though it doesn't seem to be valid JSON?
From Instapaper API Docs:
Instapaper strings are always encoded in UTF-8, and Instapaper expects all input to be in UTF-8.
Unless otherwise noted, output from every method is an array. The output array is returned as JSON by default.
You can specify a jsonp parameter with a callback function name, e.g. jsonp=myCallback, to use JSONP and wrap the output in a call to the specified function.
So there is no way you will get not valid JSON!
Try following code:
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL urlWithString:#"http://your-instapeper-API-link"] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id serializationJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
And then you can log what is wrong or if result is what you expect:
NSLog(#"class of JSON input: %# \n and possible error: %#",[serializationJSON class],error);
Of course you should expect Array and no error.
EDIT ... based on coment code:
Based on docs you should get Array or Dictionary. Please add this core instead your line #23 (numer from here):
if([JSON isKindOfClass:[NSDictionary class]]) {
NSDictionary *jsonDictionary = JSON;
NSLog(#"%#",[jsonDictionary allKeys]);
} else {
NSLog(#"JSON object class: %#",[JSON class]);
}
and please show us output.
One more thing:
You get array from request. Great! This is a valid JSON. So you need to debug it. As i said it's a shame is not a unlimited acccess public API, so i can look into it. But now you have to debug your result. I see in your code that you are trying to access bookmarks. So i look into Bookmarks section in docs and this is some kind of list (NSArray). So if you don't know what result you want. You should print them into log (or set a breakpoint). Replace code from my earlier update with this simple log:
NSDictionary *resultDictionary;
if([JSON isKindOfClass:[NSArray class]]) {
NSArray *jsonArray = JSON;
NSLog(#"so json is an array with %i objects",[jsonArray count]);
for(id objectInsideArr in jsonArray) {
NSLog(#"object in array [class]: %# [value]: %#",[objectInsideArr class],objectInsideArr); //if here you find NSDictionary maybe is this dictionary you are looking for. I'm not sure what it is.
if([objectInsideArr isKindOfClass:[NSDictionary class]]) {
resultDictionary = [[NSDictionary alloc] initWithDictionary:objectInsideArr];
}
}
}
If it were me I would write a custom formatter to get it into JSON format and then use NSJSONSerialization once I know it is valid. What you posted is so far from valid there is no way it would work. I'm surprised they are returning it in that format, do they provide some kind of library for consuming their services?
If you want something even simpler, I can give you my CGIJSONObject library that will handle JSON using reflection - you just need to mirror the keys in APIs with your classes andit is good to go.

Getting data from API, need to filter results

I'm working with data from a Foursquare API.
I want to get a list of coffee shops, and am getting that back correctly (I'm using RestKit)... but once I get that list, on my end I need to filter out any coffee shop that is a "Starbucks".
So right now I only know how to pull in all coffee shops, but I don't know how to parse that data once I have it before I serve it into the app table view so that there will be no Starbucks coffee shops listed.
Any ideas how I could do that? Let me know if you need any of my code snippets posted that might help. Thanks!
EDIT
Normal response type from the API would be:
"venue": [{
"name": "ABC Coffee Shop", {
So I would need to take "name" and filter out any name that was "Starbucks".
If FourSquare doesn't let you apply a filter to the request, to filter on the name "Starbucks" then what I would do with this is the following.
I would start by deserializing the response into a JSON Object, which in this case will be a dictionary.
NSError *error = nil;
NSDictionary *responseDict = [[NSJSONSerialization JSONObjectWithData:foursquareResponse options:0 error: &error];
NSArray *starbucks = nil;
if (!error) {
NSArray *coffeeShops = responseDict[#"venue"];
starbucks = [coffeeShops filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"name = 'Starbucks'"]];
} else {
// handle the error
}
NSLog(#"Starbucks: %#", starbucks");
I didn't test this code but I think it should get you on your way.
Looks like JSON to me, you could just use the built in JSON parser, the NSJSONSerialization class. Here is a method I built that takes an NSData JSON parameter, deserializes it and returns a dictionary.
- (NSMutableDictionary *)deserialize: (NSData *)data {
return [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error: nil] mutableCopy];
}
I don't know the structure of Foursquare's response inside out, so you might want to NSLog() the returned dictionary to see how you can now reference to it.

Resources