NSJSONSerialization can't handle null values - ios

I have some code that looks like this:
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSArray *arrRequests = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
// Loop through the array and generate the necessary annotation views
for (int i = 0; i<= arrRequests.count - 1; i++)
{
//now let's dig out each and every json object
NSDictionary *dict = [arrRequests objectAtIndex:i];
NSString *is_private = [NSString
stringWithString:[dict objectForKey:#"is_private"]];
...
It works when the value for is_private is 1 or 0, but if it is null it crashes with an exception on this line:
NSString *is_private = [NSString stringWithString:[dict objectForKey:#"is_private"]];
Is there a way to check if it is not null or handle this so that it is able to put nil into the NSString *is_private variable?
Thanks!

You should be able to handle it like so:
id value = [dict valueForKey:#"is_private"];
NSString *is_private = [value isEqual:[NSNull null]] ? nil : value;

Your problem has nothing to do with NSJSONSerialization and everything to do with the fact that you're passing a nil value to stringWithString:. Why not just simply that line to NSString *is_private = [dict objectForKey:#"is_private"];?
Also, why are you using an NSString to store a boolean value? An NSNumber would be much better-suited.

Why don't you just check if [dict objectForKey:#"is_private"] is nil or [NSNull null] before passing it to stringWithString:?

Related

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

Parsing of JSON array returning blank array

I have an array which is of below kind.
{"Hotweeks":[{"Image":"http://www.example.com/wp-content/uploads/0970E01L.jpg","Description":"Ocean Shores, WA","PostTitle":"Windjammer Condominiums"},
{"Image":"","Description":"","PostTitle":"0970O01L"},
{"Image":"","Description":"","PostTitle":"0970I08L"},
{"Image":"","Description":"","PostTitle":"0970I06L"},
{"Image":"","Description":"","PostTitle":"0970I04L"},
{"Image":"","Description":"","PostTitle":"0970i03L"},
{"Image":"","Description":"","PostTitle":"0970I02L"},
{"Image":"","Description":"","PostTitle":"0970I01L"},
{"Image":"","Description":"","PostTitle":"0970E02L"},
{"Image":"","Description":"","PostTitle":"0970E01L"},
{"Image":"http://www.example.com/wp-content/uploads/0936E01L.jpg","Description":"Manson, WA","PostTitle":"Wapato Point"},
{"Image":"","Description":"","PostTitle":"0936O05L"},
{"Image":"","Description":"","PostTitle":"0936O04L"},
{"Image":"","Description":"","PostTitle":"0936O03L"},
{"Image":"","Description":"","PostTitle":"0936O02L"},
{"Image":"","Description":"","PostTitle":"0936O01L"},
{"Image":"","Description":"","PostTitle":"0936I01L"},
{"Image":"","Description":"","PostTitle":"0936E03L"},
{"Image":"","Description":"","PostTitle":"0936E02L"},
{"Image":"","Description":"","PostTitle":"0936E01L"}]}
Which I am trying to parse using the below code.
NSArray *array = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);
This is returning null in Nslog.
…"Description":"Ocean Shores, WA,"PostTitle":…
is missing a " after Ocean Shores, WA. It should be
…"Description":"Ocean Shores, WA","PostTitle":…
Use a JSON validator to check for this type of thing. There are many to pick from. I use the Chrome apps JSON Lint and JSON Editor.
The top level of your Json file is an object, not an array (it doesn't start with '['). That being said, if you check array's type like this: NSLog("%#", [array class] you'll probably see it's a NSDictionary.
To get the array you can do this:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSArray *array = jsonDict[#"Hotweeks"];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);

Parse from JSON response

I am getting the JSON response
(
{
Response = success;
UserId = 287;
}
)
I tried to parse the user id with below code
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataDictionary);
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
But am getting the user id ( 287 ).
Please suggest me that how to get user id without paraparentheses
Your response is not a dictionary, it's an array. So your code should look like this:
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataArray);
NSDictionary *dataDictionary = dataArray[0]; //Same as objectAtIndex:
NSString *userIDString = dataDictionary[#"UserID"]; //Same as objectForKey:
//If you're still getting parens try this:
//int userIDInt = [dataDictionary[#"UserID"] intValue];
You need to fetch integer value from your JSON response.
int userid = [[dataDictionary valueForKey:#"UserId"] intValue];
If getting parentheses in integer response too, then it is problem with JSON response recived. for a workaround you can use -
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
int userid = [[useridstring substringWithRange:NSMakeRange(1, useridstring.length - 2)] intValue]
EDIT --
You are getting an array in response, for this you have to use -
int userid = [[dataDictionary valueForKey:#"UserId"] firstObject];

How to get key/value pair from NSDictionary?

I need little help with NSDictionary. How can I get 1 pair, lets say a value for "id" if I have dictionary
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
and it looks like this:
Thanks for Your help.
The shortest way:
NSNumber *number = allCourses[#"semacko"][#"id"];
Try this:
NSDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:NSJSONReadingMutableContainers error:&error];
[allCourses enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
// do something with key and obj
}];
NSDictionary *semacko = [allCourses objectForKey:#"semacko"];
NSNumber *number = [semacko objectForKey:#"id"];
NSNumber *number = allCourses[#"semacko"][#"id"];
or if you want to iterate all objects:
for(NSDictionary* course in allCourses) {
NSNumber *number = course[#"id"];
}
NSString *name =[[NSString alloc]initWithFormat:#"%#",[Dictionaryname objectForKey:#"key"]];
by this code you can access the value that corresponds to the key that specified in the objectforkey keyword
You can try:
NSNumber *courseID = [allCourses valueForKeyPath:#"semacko.id"];
For setting value:
- setValue:forKeyPath:

Cant access serialized JSON data (NSJSONSerialization)

I get this JSON from a web service:
{
"Respons": [{
"status": "101",
"uid": "0"
}]
}
I have tried to access the data with the following:
NSError* error;
//Response is a NSArray declared in header file.
self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *test = [[self.response objectAtIndex:0] objectForKey:#"status"]; //[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSString *test = [[self.response objectForKey:#"status"] objectAtIndex:0]; //(null)
But none of them work, if i NSLog the NSArray holding the serialized data, this i what i get:
{
Respons = (
{
status = 105;
uid = 0;
}
);
}
How do i access the data?
Your JSON represents a dictionary, for whom the value associated with the Respons key is an array. And that array has a single object, itself a dictionary. And that dictionary has two keys, status and uid.
So, for example, if you wanted to extract the status, I believe you need:
NSArray *array = [self.response objectForKey:#"Respons"];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *status = [dictionary objectForKey:#"status"];
Or, in latest versions of the compiler:
NSArray *array = self.response[#"Respons"];
NSDictionary *dictionary = array[0];
NSString *status = dictionary[#"status"];
Or, more concisely:
NSString *status = self.response[#"Respons"][0][#"status"];
Your top level object isn't an array, it's a dictionary. You can easily bypass this and add the contents of that key to your array.
self.response = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] objectForKey:#"Respons"];

Resources