NSJSONSerialization NSJSONReadingAllowFragments reading - ios

In the following code for parsing a JSON, when objects happen to be other than NSArray or NSDictionary, NSJSONReadingAllowFragments is used.
The below code works fine and prints out 32. but if replace 32 by abcd, it outputs to null.
Any idea why its null for a string abcd.
NSString *num=#"32";
NSError *error;
NSData *createdData = [num dataUsingEncoding:NSUTF8StringEncoding];
id response=[NSJSONSerialization JSONObjectWithData:createdData options:NSJSONReadingAllowFragments error:&error];
NSLog(#"Response= %#",response);

That’s because 32 is a valid JSON fragment (a number), but abcd is not a valid JSON fragment since all strings must be quoted. Try:
NSString *num=#"\"abcd\"";
which produces "abcd" instead of abcd.
(also, bear in mind that the object being returned is not really an NSDictionary, so declaring it as id makes more sense)

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.

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.

How to get an integer value from NSDictionary?

I am having this weird issue. NSDictionary is not returning the correct integer value.
JSON response code from server.
{
"status":"ok",
"error_code":0,
"data" : [],
"msg":"everything is working!"
}
The JSON is being converted to a NSDictionary.
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error: &error];
I access the NSDictionary value using the following code.
int error_code = (int)[jsonDict valueForKey:#"error_code"]
NSLog(#"%i", error_code);
The log outputs the following: 143005344
I've even tried objectForKey and I get the same response.
Thanks, in advance.
Yes it outputs the pointer of the value and that's why you see this log output.
You cannot cast the pointer to an integer and expect the value.
int error_code = [[jsonDict valueForKey:#"error_code"] integerValue];
or if you want to use modern objective-c
int error_code = [jsonDict[#"error_code"] integerValue];
Numbers are stored as NSNumber instances in plist/json dictionaries. Try calling one of NSNumber's getters like intValue:
int error_code = [jsonDict[#"error_code"] intValue];
Note also the new subscripting syntax for dictionaries.

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
}

Resources