Creating JSON with iOS 5 - issues - ios

I'm trying to create a JSON object that looks like this:
{ "request_type":"send_string" "security_level":0 "device_type":"ios" "blob":{"string":"blah"}"}
Here's my attempt:
NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
sendString,#"string",
nil];
NSString *blobString = [[NSString alloc]
initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
encoding:NSUTF8StringEncoding];
NSLog(#"Blob Created: %#", blobString);
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"send_string",#"request_type",
0,#"security_level",
#"ios",#"device_type",
//No Email Provided, This is just for testing
blobString,#"blob",
nil];
NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
NSLog(#"Proper JSON Object");
JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else {
NSLog(#"requestData was not a proper JSON object");
return FALSE;
}
NSLog(#"%#",[[error userInfo] objectForKey:#"NSDebugDescription"]);
NSLog(#"%#",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]);
The problem is, that last NSLog tells me all I've created is something like this:
{"request_type":"send_string"}
So when I go and try to write this to the server with
[NSJSONSerialization writeJSONObject:JSONRequestData toStream:outputStream options:0 error:&error];
I get this error from the console:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write'

Replace this line
0,#"security_level"
with
[NSNumber numberWithInt:0],#"security_level"

Related

-[__NSSingleObjectArrayI dataUsingEncoding:] Objective C

My JSON string is
"{\"CommentList\":[{\"SubmittedDate\":\"02/01/2017 06:09:32\",\"SubmittedTime\":\"\",\"UserId\":\"af0e1cda5c0\",\"UserName\":\"NepolionBon\",\"Comments\":\"\",\"Complete_Hour\":\"\",\"Complete_Minute\":\"\"}]}"
I need value of "SubmittedDate" and "Complete_Hour" from it.
When I'm trying to convert this string with
NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
getting an error saying
-[__NSSingleObjectArrayI dataUsingEncoding:]: unrecognized selector sent to instance 0x14decfc0
can anyone help me?
You can use this code to get SubmittedDate and Complete_Hour.
NSString *jsonString = #"{\"CommentList\":[{\"SubmittedDate\":\"02/01/2017 06:09:32\",\"SubmittedTime\":\"\",\"UserId\":\"af0e1cda5c0\",\"UserName\":\"NepolionBon\",\"Comments\":\"\",\"Complete_Hour\":\"\",\"Complete_Minute\":\"\"}]}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray* arrComments = [json objectForKey:#"CommentList"];
for (NSDictionary *dict in arrComments) {
NSLog(#"Submit date :%#",[dict objectForKey:#"SubmittedDate"]);
NSLog(#"Comlplete Hour : %#",[dict objectForKey:#"Complete_Hour"]);
}

Creating Objects from template crashes with error: "NSInvalidArgumentException"

This function is intended to get a JSON and make an array of objects based on the object sent as parameter:
+ (NSArray *)Object: (id) object FromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
return nil;
}
NSMutableArray *output = [[NSMutableArray alloc] init];
NSArray *results = [parsedObject valueForKey:#"results"];
NSLog(#"Count %lu", (unsigned long)results.count);
for (NSArray *eventDic in results) {
object = [[[object class] alloc] init];
for (NSString *key in eventDic) {
if ([object respondsToSelector:NSSelectorFromString(key)]) {
[object setValue:[eventDic valueForKey:key] forKey:key];
}
}
[output addObject:object];
}
return output;
}
But it is crashing every time I run it. I get this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x1100c3ce0'
I am new to iOS programming and have no idea what this means.
NSArray *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
Pass 0 if you don't care about the readability of the generated string
if you want to parsed object as NSArray, change your options as NSJSONReadingMutableContainers
NSDictionary *dic_JSON = [NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: &error];

unrecognized selector sent to instance AFNetworking [duplicate]

Update: I just tested my JSON format returned from the server using JSONlint and it is fine.
I'm getting an exception with NSJSONSerialization in an AFNetworking call to a php script that returns JSON data. I've looked at the other questions here with the same issue and tried those solutions but am still getting the error.
It crashes on this line:
NSError *e = nil;
NSMutableArray *jsonArray =
[NSJSONSerialization JSONObjectWithData: jsonData
options: NSJSONReadingMutableContainers
error: &e];
Error Log:
2012-03-19 18:10:41.291 imageUploader[3538:207] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray bytes]: unrecognized selector sent to instance 0x6867430'
My JSON data, when I call the php script through the browser looks like this:
[{"user":"binky","path":"binky-0a96f9aab5267c8.jpg","index":"101"},{"user":"binky","path":"binky-9cf844252c28553.jpg","index":"102"},{"user":"binky","path":"binky-d6c749d25d33015.jpg","index":"103"}]
The NSLog of the data looks like this:
(
{
index = 101;
path = "binky-0a96f9aab5267c8.jpg";
user = binky;
},
{
index = 102;
path = "binky-9cf844252c28553.jpg";
user = binky;
},
{
index = 103;
path = "binky-d6c749d25d33015.jpg";
user = binky;
} )
Finally, I do a test to make sure I have valid JSON data:
if ([NSJSONSerialization isValidJSONObject: jsonData]){
NSLog(#"Good JSON \n");
}
So I can't understand where the source of my error is. Little help?
// AFNetworking operation + block
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:myRequest
success:^(NSURLRequest *request, NSHTTPURLResponse *response, id jsonData) {
NSLog(#"Success JSON data:\n %# \n", jsonData); //log data
if ([NSJSONSerialization isValidJSONObject: jsonData]){
NSLog(#"Good JSON \n");
}
NSError *e = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
[self.navigationController popToRootViewControllerAnimated:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Error: %#", error);
[self.navigationController popToRootViewControllerAnimated:YES];
}];
Aparently JSONObjectWithData expects NSData rather than an array.
id jsonData seems to be an Array representing the content of your json string. Aparently you are expecting an Array anyway.
For some reason you are doing it twice. Instead of
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &e];
you could simply use
NSMutableArray *jsonArray = [NSMutableArray arrayWithArray:jsonData];
or, if it does not have to be mutable:
NSArray *jsonArray = (NSArray *) jsonData;
However, you should always test whether it is really an array in jsonData. Depending on the structure within the json string it could be an NSDictionary or nil in case of errors.

iOS 7 NSJSONSerialization

I am trying to develop an app that parses json data. I have the following json :
{
myobject:[
{
id:184,
title: "test title"
}
]
}
I have the following code which im trying to get the title data from this json
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(#"%#",error);
}
NSDictionary *nar = [currentObject objectForKey:#"myobject"];
NSLog(#"%#",[nar valueForKey:#"title"]);
NSString *curTitle = [nar valueForKey:#"title"];
self.myTitle.text = curTitle;
When I log the title, I can see that the title is indeed coming back. However, when I try to set the myTitle.text I get the following error
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x15631850
In your json my object field is not a dictionary, but array of dictionaries, so [nar valueForKey:#"title"] will return array of valueForKey for each of elements in that array.
If you're sure about data format you can extract string value from it the following way:
 NSArray *nar = [currentObject objectForKey:#"myobject"];
NSString *curTitle = nar[0][#"title"];
But of course it is better to add some data validation/error handling in production code.
It is crash because Your dictionary contain NSArray, not dictionary.
NSArray *ar = [currentObject objectForKey:#"myobject"];
for(NSDictionary *dict in ar)
{
NSLog(#"%#", [dict objectForKey:#"title"];
)
}
NSString *curTitle = [[ar objectAtIndex:0] objectForKey:#"title"];
self.myTitle.text = curTitle;
You are trying to assign NSArray to self.myTitle.text.
NSData *jsonData = [NSData dataWithContentsOfURL:myURL];
NSError *error = nil;
NSDictionary *currentObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if(error)
{
NSLog(#"%#",error);
}
NSArray *nar = [currentObject objectForKey:#"myobject"];
NSString *title = [[nar objectAtIndex:0] objectForKey:#"title"];
NSLog(#"%#",title);
self.myTitle.text = title;

NSJSONSerialization misbehaves, 98% of the time returns array, other 2% returns dict

This is really very odd.
We're accessing a json Twitter API that always returns an array.
ie
https://twitter.com/statuses/user_timeline/485963081.json
We do:
if([NSJSONSerialization class]) {
NSError *error = nil;
jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
DLog(#"JSON Parsing Error: %#", error);
} else {
NSString * jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
jsonResponse = [jsonString JSONValue];
}
if([jsonResponse count] > 0) {
NSString *jsonText = [[jsonResponse objectAtIndex:0] objectForKey:#"text"];
twitterText = jsonText;
}
This works a vast majority of the time. The rest, we get this:
[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
Note, all the errors are on iOS5, so the SBJSON library does not apply.
Sometimes NSJSONSerialization parses the array as a dict. Which frankly, is not possible using the data from twitter. So what's happening here?

Resources