Weird sorting when parsing JSON - ios

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.

Related

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

JSon array to core data entity

I have a cuestion about parsing a Json strings.
If i'm getting a string like:
[["AR","Argentina","flag_of_argentina","en","F","1"],
["AU","Australia","flag_of_‌​australia","en","B","4"]]
How can i save this string into an entity when normally i see Jsons that have something like this:
(
(
"Group_id": 1,
"Date" : "2014-04-08",
"Hour" : "18:00:00",
"Location":"Guayaquil, Ecuador",
"State" : A
),
...
If i have to make an array or something else to store it to the entity in core data how can i do it?
I hope my question is well made ​​and I appreciate your help. Thank you very much.
Cocoa Touch provides a built in class that helps you serialize this data. It's called NSJSONSerialization.
So, that looks to me like you have arrays within an array. First you're going to want to convert the NSString to NSData:
NSData *JSONdata = [yourJSONString dataUsingEncoding:NSUTF8StringEncoding];
Then serialize it into an array:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:JSONdata options:NSJSONReadingMutableContainers error:&error];
Then you can access any subarray by writing:
NSArray *countryData = [JSONArray objectAtIndex:i];
And from there you can access the data that you need.
~
As for building JSON Data, you'll need to construct an NSMutableDictionary and populate it accordingly. Once you have that, use the same class NSJSONSerialization to convert it to a JSON string.

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.

Parse double quotes and single quotes in Json Parsing

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
}

Parsing JSON response with multiple objects

I've got a question regarding parsing a JSON response within iOS5.
Currently, I'm following this guide here to help me parse the JSON response returned from a third-party mapping service.
Everything works, except that the JSON response returned by the third-party server is somewhat different from the one shown in the guide itself.
In a nutshell, the overall structure of the entire JSON response looks something like this:
{
"directions": [....],
"messages": [....],
"routes":
{
"features": [
{
"attributes": {....},
"geometry":
{
"paths": [....]
}
}
]
}
}
This is the actual JSON query URL.
By using this line of code,
NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
I am able to sucessfully get the jsonResponse dictionary to report that it has 3 key/value pairs, but my ultimate goal is to retrieve the array stored in 'routes.features.geometry.paths'.
This is my current code block that gets the final set of array values:
NSDictionary * jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray * jsonArray = [jsonResponse valueForKeyPath:#"routes.features.geometry.paths"];
jsonArray = [jsonArray objectAtIndex:0];
jsonArray = [jsonArray objectAtIndex:0];
I was wondering if anyone might have a better idea of how I should go about doing this in a more elegant fashion?
Thanks a lot in advance!
You can't just use it as JSON object because it will be working as JSON (Plain String) and you need to parse it so for your problem you can do like this to directly go to paths
NSArray *arr = [[[[jsonResponse objectForKey:#"routes"] objectForKey:#"features"] objectForKey:#"geometry"] objectForKey:#"paths"];
Now you can access your paths data from "arr" array
UPDATE:
NSArray *arr = [[[[[jsonResponse objectForKey:#"routes"] objectForKey:#"features"] objectAtIndex:0] objectForKey:#"geometry"] objectForKey:#"paths"];
as features element is an Array so traverse array first then goto its elements

Resources