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;
Related
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"]);
}
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];
In my app, I am parsing the data using JSON
NSString * urlString=[NSString stringWithFormat:#"http://userRequest?userid=bala#gmail.com&latitude=59.34324&longitude=23.359257"];
NSURL * url=[NSURL URLWithString:urlString];
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError * error;
NSURLResponse * response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * outputData=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",outputData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:outputData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
After this code executes, In my log it is printed as
({
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},
{
latitude = "80.000000000000000";
longitude = "30.000000000000000";
username = arun;
})
But while running, the app crashes, as
'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x910d8d0'
I think your problem is, that jsonParser objectWithString returns an array with dictionaries in it not dictionaries itself.
Try the following:
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
for(NSDictionary *dict in jsonData) {
NSLog(#"%#",dict);
}
Does that work for you ?
Your reponse is NSArray which contains NSDictionary. So frst get dictionary from array then access value. Also Your json not look like correct.
for (NSDictionary *dict in responseArray) {
double latitude = [dict[#"latitude"]doubleValue];
double longitude = [dict[#"latitude"] longitude];
NSString* name = dict[#"username"];
}
1. First of all you are getting NSArray in JSON
JSON Starts with "(" means NSArray
JSON Starts with "{" means NSDictionary
Here you are getting NSArray which has collection of NSDictionary,
{
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},...
2."success" key is not present in the JSON..
Fix
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
If([jsonData count]>0){
// Has some data
// Iterate NSDictionary and get data here
}
else{
// No Data
}
some where you are getting data from nsarray with using some object key. that key is invalid to fetching data from array
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"
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?