JSONSerilazation not working while parsing JSON object - ios

I am getting an error while parsing the NSData I got from a server.
I am unable get the NDIctinory.
I am getting the error "No string key for value in object"
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:[body dataUsingEncoding:NSUTF8StringEncoding]
options:kNilOptions
error:&error];
Could someone help me with this issue?

The error message says that in the object (that's what JSON calls a dictionary) there is a key that is not a string, i. e. a number or another object. This is invalid.
From RFC7159, 4:
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string.
Therefore you will have an invalid JSON. Change that, if possible. Aditionally you can post the whole JSON in your Q. (Not in a comment to this A.)

Related

NSJSONSerialization encoding?

I'm trying to convert my NSDictionary to a json string and then send the data to my web api via HTTPBody (POST request). I convert my dictionary to json like this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
What I found is that this above method, is not encoding my data (at least special characters like ampersand is not being handled). So the data received on the server side is a mess and I can't read it properly.
For more details on what is happening, assume the following dictionary:
"salutation":"Mrs."
"companyName":"T & F LLP"
"firstName":"Tania"
"country":"Canada"
This dictionary is converted to NSData using the above method and later used like this
[request setHTTPBody:nsDataFromJson];
What do I receive on the server side? I get this
{"contact":"{\"firstName\":\"Tania\",\"salutation\":\"Mrs.\",\"company\":\"Aird
I only get the data up to the special character & and I can only assume that this is happening because the first method I mentioned is not encoding special characters like the &
So I solved this (just for the time being) by converting the dictionary into a json string then replacing each & with %26 then creating NSData from this new string (with the special characters handled). Then I get the full body on my server.
So any idea how to properly handle this?
By the way, the same problem occurs if I use SBJSON too.
It has been 3 months, so I guess the problem must have been solved by now.
The reason the received JSON data is corrupted is because the parser interpreted & (ampersand) as a part of the URL address. Borrowing some codes from this link, I wrote this function to percent-encode & and a few other characters that may get confused:
+ (NSDictionary*) percentEncodeDictionayValues:(NSDictionary*) dict
{
NSMutableDictionary* edict=[NSMutableDictionary dictionaryWithDictionary:dict];
NSMutableCharacterSet* URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:#"?&=#+/'"];
for(NSString* key in [dict allKeys])
{
if([dict[key] isKindOfClass:[NSString class]])
edict[key] = [dict[key] stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
}
return edict;
}
So you can preprocess your NSDictionary object with this function before feeding into NSJSONSerialization, and the received data will have & and other characters preserved.

Couldn't Serialize NSData Objective C

I couldnt serialize the following JSON data. I can't see anything wrong in it.
[{"id":2182,"title":"HEAVEN ON EARTH","content":"Description","post_date":"2014-07-28 09:29:45","post_modified":"2014-07-28 09:29:45","abc_featured":"","abc_rating":"0","abc_recommended":"","abc_phone":"","abc_address":"","abc_address2":"","abc_postcode":"","abc_suburb":"","abc_state":"NSW","abc_website":"http:\/\/","abc_email":"Pralead#hotmail.com","abc_lat":"-1000","abc_lon":"10000","abc_closed_txt":"","yes_event":"","from_event_date":"","to_event_date":"","abc_location":"","abc_age":"","abc_cost":"","abc_prebook":"","abc_parentaccompany":"","abc_changingfaciltiy":"","abc_playarea":"","abc_pramaccessibility":"","abc_breastfeedingarea":"","abc_refreshments":"","abc_inoutdoor":"","abc_parking":"","abc_freetrail":"","feature_name":null,"feature_value":null,"feature_available":[],"image1":"http:\/\/localhost\/wordpress\/wp-content\/uploads\/2014\/07\/IMG_0014.png","image2":"http:\/\/localhost\/wordpress\/wp-content\/uploads\/2014\/07\/IMG_0011.png","image3":"http:\/\/localhost\/wordpress\/wp-content\/uploads\/2014\/07\/IMG_0009.png","Monday_from_time":"","Monday_to_time":"","Tuesday_from_time":"","Tuesday_to_time":"","Wednesday_from_time":"","Wednesday_to_time":"","Thursday_from_time":"","Thursday_to_time":"","Friday_from_time":"","Friday_to_time":"","Saturday_from_time":"","Saturday_to_time":"","Sunday_from_time":"","Sunday_to_time":""}]
CODE TO SERIALIZE IS:
NSArray *jsonArray=[NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
_downloadedData is the data I am geting from the JSON API.
I CAN SEE THE DATA COMING THROUGH THE NSLOG.
At a minimum the JSON in the question has problems, the main one is "null" for the value of a dictionary item.
Ex: "feature_name":null.
NSDictionary values must be an object.
Is the JSON in the question a NSLog() of _downloadedData?

iOS RestKit 0.2 What is the best way to parse local Json

I wave read many articles about parsing a json via an Http request but almost none answers the question about what is the most straight forward way to parse o local json string. I found some deferent solutions here Deserializing local NSString of JSON into objects via RestKit (no network download) some of them work some others don't. Is there any "official" RestKit support for local JSON string deserialization?
Fortunately Apple provides "NSJSONSerialization" class from iOS 5.0. to serialise your data.
Step 1 : convert your local JSON string to "NSData"
NSString *strLocalJSON = #"{data= "some data"}"; //just for ex. may not be valid one
NSData *dataJSON = [str dataUsingEncoding:NSUTF8StringEncoding];
Step2:
id jsonobject= [NSJSONSerialization JSONObjectWithData:dataJSON options:NSJSONReadingMutableContainers error:nil]; // resulting object may contain Dictionary or Array depends on your localjson
for further info refer https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
If your JSON is in a file then you use a file:// NSURL when you create your RestKit object manager. Everything else works as normal.
If the JSON is already in code, then you should save it to a file, or why are you needing to do any mapping? Anyway, you could use a combination of NSJSONSerialization and RKMappingOperation.

How to extract a value from a key/value pair in NSDictionary (iOS)

When debugging in XCode, the debugger is telling me that the NSDictionary object contains 1 key/value pair. When the debug console prints the description of the key/value pair is shows:
Printing description of testdictionary:
{
"Unknown (<1809>)" = <000000ff>;
}
I want to extract both the <1809> and the <000000ff>. I have tried both the valueForKey and objectforKey methods as described elsewhere on this site. But I think I am having difficulty understanding what is the key and what is the value here.
For example, is "Unknown (<1809>)" the key? Or is "<1809>" the key? Or is 1809 the key?
Thanks Tim for the reply.
The NSDictionary comes from the CoreBluetoothFramework the didDiscoverPeripheral: method is called and passes advertising data into an NSDictionary called "advertisementData".
This dictionary contains all sorts of stuff like the advertising channel and device name. However, I am trying to extract just the advertising data from "advertisementData". I used the key provided by corebluetooth "CBAdvertisementDataServiceDataKey" like this:
NSData* information;
information = [advertisementData objectForKey:CBAdvertisementDataServiceDataKey];
I was declaring "information" as an NSDictionary* object before. But changed it to NSData* after some more reading on Apples documentation. The result is the same. The debugger says that it contains a key/value pair as follows:
"Unknown (<1809>)" = <000000ff>;
Thanks again.
Nik
When you do not know the keys that are present in the dictionary, for example, because the key-value pairs come from an external source, you can use enumerateKeysAndObjectsUsingBlock: method to go through all key-value pairs present in the dictionary:
[testdictionary enumerateKeysAndObjectsUsingBlock::^(id key, id object, BOOL *stop) {
NSLog(#"The key is %#", key);
NSLog(#"The value is %#", object);
}];
I've never seen this before so this is nothing more than an educated guess:
The dictionary may have been casted from CFDictionaryRef, in which case both the key and value are const void * (instead of NSObject). The key might have been some Core Foundation type holding a file descriptor (hence 1809). The value could be a pointer (or an integer casted to a "pointer": (void *)32).
You should try and find out where the dictionary originates from, because it's the only thing that's going to give you any valuable information.
Update: the docs state that the value of CBAdvertisementDataServiceDataKey is a dictionary. The keys are CBUUID objects, representing CBService UUIDs and the values are NSData objects. (1)

Parsing JSON string with different local (no english)

I got below JSON string, i facing issue parsing because it contains non english local:
{"error":0,"token":"59188a107d705f8c51585d719769e0642ce98b79d86fdace30dbc58efba301cc","status":"200","messages":[{"update_time":"2012-03-31
22:50:13","seq":"497","lng":58.4235,"msg":"hhhh : ≈∏?≈∏?
ÿ™ÿ™ÿߟ?ÿ™ ","lat":23.5866}],"error_msg":""}
i'm trying with below code:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
it works fine if it's in English only, how could I parse non english local in JSON.
From the docs:
The data must be in one of the 5 supported encodings listed in the JSON specification: UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. The data may or may not have a BOM. The most efficient encoding to use for parsing is UTF-8, so if you have a choice in encoding the data passed to this method, use UTF-8.
Since your string does not appear correctly in Safari, I suspect that it is not encoded in one of these formats. You would need to re-encode your data into a legal JSON encoding.

Resources