Can someone please help me in parsing the below jsonData into a nsDictionary object
[ { "id": "22144" ,"t" : "AAPL" ,"e" : "NASDAQ" ,"l" : "111.57"
,"l_fix" : "111.57" ,"l_cur" : "111.57" ,"s": "2" ,"ltt":"4:00PM EST"
,"lt" : "Nov 28, 4:00PM EST" ,"lt_dts" : "2016-11-28T16:00:01Z" ,"c" :
"-0.22" ,"c_fix" : "-0.22" ,"cp" : "-0.20" ,"cp_fix" : "-0.20" ,"ccol"
: "chr" ,"pcls_fix" : "111.79" ,"el": "111.56" ,"el_fix": "111.56"
,"el_cur": "111.56" ,"elt" : "Nov 28, 8:00PM EST" ,"ec" : "-0.01"
,"ec_fix" : "-0.01" ,"ecp" : "-0.01" ,"ecp_fix" : "-0.01" ,"eccol" :
"chr" ,"div" : "0.57" ,"yld" : "2.04" } ]
#define QUERY_PREFIX #"https://www.google.com/finance/info?q=NSE:AAPL"
#define QUERY_SUFFIX #"NSE:AAPL"
#implementation YQL
- (NSDictionary *) query: (NSString *)statement {
NSString *query = [NSString stringWithFormat:#"%#%#%#", QUERY_PREFIX, [statement stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding], QUERY_SUFFIX];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSString *dataString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSUInteger firstCurlyBracePos = [dataString rangeOfString:#"[" options:0].location;
NSUInteger lastCurlyBracePos = [dataString rangeOfString:#"]" options: NSBackwardsSearch].location;
NSString *jsonString = nil;
if(firstCurlyBracePos != NSNotFound && lastCurlyBracePos != NSNotFound) {
jsonString = [dataString substringWithRange:NSMakeRange(firstCurlyBracePos, (lastCurlyBracePos-firstCurlyBracePos)+1)];
}
NSData *someData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%# Nirmal",jsonString);
NSError *error = nil;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:someData options:0 error:&error];
NSLog(#"%# Anand",results);
NSString* latestLoans = [results objectForKey:#"el_cur"];
NSLog(#"loans: %#", latestLoans);
if (error) NSLog(#"[%# %#] JSON error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
return results;
}
#end
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSSingleObjectArrayI
objectForKey:]: unrecognized selector sent to instance 0x61800000d010'
The JSON you're trying to parse is an array, not an object, as denoted by the enclosing square brackets. So NSJSONSerialization is going to return an NSArray here, not an NSDictionary. Since it seems like there is only one object in this array, you can access it like so:
NSArray *results = [NSJSONSerialization JSONObjectWithData:someData options:0 error:&error];
NSDictionary *object = results.firstObject;
NSString *latestLoans = object["el_cur"];
Related
Made a custom table view controller in which call a service in viewDidLoad method. The service is called with some parameters and it is GET request. The response is coming fine but it is showing an exception error this,Terminating app due to uncaught exception
'NSUnknownKeyException', reason: '[<__NSCFString 0x60000036a140> valueForUndefinedKey:]: this class is not key value coding-compliant for the key data.'
My response from service is this
{"data":[{"id":"139559","first_name":"Shoaib Anwar","last_name":null,"address":null,"mobile":"03233008757","city":null,"date":"2017-08-10","date_of_birth":"1992-08-10"}]}.
The app crashes all the time , i'm confused why it is showing this error.
My code is this,
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"number"];
NSString *url=#"My Url";
NSString *string3 = [url stringByAppendingString:savedValue];
NSString *lastArray = #"&type=json";
string3 = [string3 stringByAppendingString:lastArray];
NSLog(#"Mmm %#",savedValue);
NSLog(#"Mmm %#",string3);
NSString *targetUrl = [NSString stringWithFormat:#"%#",string3];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:targetUrl]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data,
NSURLResponse * _Nullable response,
NSError * _Nullable error) {
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data received: %#", myString);
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
NSString *value = json[#"data"];
_Ids = [NSMutableArray array];
for (NSDictionary * oneCustomer in value)
{
// Create a new Customer record
ViewProfile * newCustomer = [[ViewProfile alloc] init];
newCustomer.ids = [oneCustomer objectForKey:#"id"];
NSLog(#"ID: %# ", newCustomer.ids);
newCustomer.fname = [oneCustomer objectForKey:#"first_name"];
NSLog(#"Fname: %# ", newCustomer.fname);
newCustomer.lname = [oneCustomer objectForKey:#"last_name"];
NSLog(#"Lname: %# ", newCustomer.lname);
newCustomer.address = [oneCustomer objectForKey:#"address"];
NSLog(#"Address: %# ", newCustomer.address);
newCustomer.mobile = [oneCustomer objectForKey:#"mobile"];
NSLog(#"Mobile: %# ", newCustomer.mobile);
newCustomer.city = [oneCustomer objectForKey:#"city"];
NSLog(#"City: %# ", newCustomer.city);
newCustomer.date = [oneCustomer objectForKey:#"date"];
NSLog(#"Date: %# ", newCustomer.date);
newCustomer.dob = [oneCustomer objectForKey:#"date_of_birth"];
NSLog(#"DOB: %# ", newCustomer.dob);
// Add our new Customer record to our NSMutableArray
[_Ids addObject:newCustomer];
}
dispatch_async(dispatch_get_main_queue(), ^{
// This code will run once the JSON-loading section above has completed.
[self.tableView reloadData];
});
NSString *status=[myString valueForKey:#"data"];
NSLog(#"Status:%#",status);
}] resume];
Your response is a json string.
Try to convert myString property to NSData type and then pass to NSJsonSerialisation class.
NSData *jsonData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
Hope this helps :)
you should comment this line
NSString *status=[myString valueForKey:#"data"];
or check your storyboard or Xib
are you have Label or Button like the image attached
Please try below code and update according to your requirement.
NSString *myString = #"{\"data\":[{\"id\":\"139559\",\"first_name\":\"Shoaib Anwar\",\"last_name\":null,\"address\":null,\"mobile\":\"03233008757\",\"city\":null,\"date\":\"2017-08-10\",\"date_of_birth\":\"1992-08-10\"}]}";
NSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *value = json[#"data"];
for (NSDictionary * oneCustomer in value)
{
// Create a new Customer record
NSLog(#"ID: %# ", [oneCustomer objectForKey:#"id"]);
NSLog(#"Fname: %# ", [oneCustomer objectForKey:#"first_name"]);
}
Crashing issue because of NSString *status=[myString valueForKey:#"data"];
The code:
NSURL * url=[NSURL URLWithString:#"alamghareeb.com/mobileData.ashx?catid=0&No=10"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSMutableArray * referanceArray=[[NSMutableArray alloc]init];
NSMutableArray * periodArray=[[NSMutableArray alloc]init];
NSArray * responseArr = [NSArray arrayWithArray:json[#"item"]];
for (NSDictionary * dict in responseArr) {
[referanceArray addObject:[dict objectForKey:#"created"]];
}
The JSON looks like:
{
"item" = [
{
"id" : "2292",
"created" : "10/01/2015 10:21:18 ص",
"title" : "الإمارات: ملابس رياضية فاخرة لتحسين أداء الإبل في السباقات ",
"image_url" : "http://alamghareeb.com/Photos/L63556482078696289044.jpg",
"image_caption" : ""
},
{
"id" : "2291",
"created" : "10/01/2015 09:28:11 ص",
"title" : "طبيبة تجميل 'مزورة' تحقن مرضاها بالغراء والاسمنت",
"image_url" : "http://alamghareeb.com/Photos/L63556478891290039015.jpg",
"image_caption" : ""
}
]
}
This JSON is not valid. Did you build it manually? The "item" = ... should be "item" : ....
In the future, you can run your JSON through http://jsonlint.com to verify any issues. Likewise, you should add error checking in your Objective-C code, e.g.
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
if (!json) {
NSLog(#"JSON parsing error: %#", error);
}
I'd also suggest changing your server code to not build JSON manually, but take advantage of JSON functions (e.g. if PHP, build associative arrays and then generate JSON output using the json_encode function).
So, once you fix the JSON error, to parse the results might look like:
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!dictionary) {
NSLog(#"NSJSONSerialization error: %#", error);
return;
}
NSArray *items = dictionary[#"item"];
for (NSDictionary *item in items) {
NSString *identifier = item[#"id"];
NSString *created = item[#"created"];
NSString *title = item[#"title"];
NSString *urlString = item[#"image_url"];
NSString *caption = item[#"image_caption"];
NSLog(#"identifier = %#", identifier);
NSLog(#"created = %#", created);
NSLog(#"title = %#", title);
NSLog(#"urlString = %#", urlString);
NSLog(#"caption = %#", caption);
}
You can use NSJSONSerialization. No need to import any class.
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[strResult dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
or use NSData directly as
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:theJSONDataFromTheRequest options:0 error:nil];
Source : Stackoveflow question
Some days ago I tryid to read and parse data from server. But today it doesn't work. What can be wrong?
Here I out my method:
-(void) getDataFromServer
{
act = #"linkinginit";
deviceid = #"1xyhgjs";
fullRequest = [NSString stringWithFormat:#"http://app.ivson.by/?act=%#&deviceid=%#", act, deviceid];
NSLog(#"%#", fullRequest);
NSURL *url = [NSURL URLWithString:fullRequest];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSData *returnData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: nil error: nil];
NSString *strData = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSRange searchedRange = NSMakeRange(0, [strData length]);
NSLog(#"Data from server = %#", strData);
NSString *json = strData;
// NSString *json = #"{\"code\":200,\"serviceID\":\"53d22b10e46a5\",\"sender\":1,\"hasPair\":0}";
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id obj = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:&error];
if (obj) {
NSAssert([obj isKindOfClass:[NSDictionary class]], #"Expected a dictionary");
NSDictionary *dictObj = (NSDictionary *)obj;
NSNumber *code = dictObj[#"code"];
NSLog(#"code:", code);
NSString *serviceId = dictObj[#"serviceID"];
NSLog(#"serviceId:", serviceId);
NSNumber *sender = dictObj[#"sender"];
NSLog(#"sender:",sender);
NSNumber *hasPair = dictObj[#"hasPair"];
NSLog(#"hasPair:", hasPair);
} else {
NSLog(#"Failed to parse JSON: %#", [error localizedDescription]);
}
}
And output is like this. I need to have all variables(code, serviceId, sender and hasPair) separate.
2014-07-28 11:46:41.640 Nanny[1445:11303] http://app.ivson.by/? act=linkinginit&deviceid=1xyhgjs
2014-07-28 11:46:41.923 Nanny[1445:15b03] ADDRESPONSE - ADDING TO MEMORY ONLY: http://app.ivson.by/?act=linkinginit&deviceid=1xyhgjs
2014-07-28 11:46:41.924 Nanny[1445:11303] Data from server = {"code":200,"serviceid":"53d60c7cc35f1","sender":1,"hasPair":0}
2014-07-28 11:46:41.924 Nanny[1445:11303] code:
2014-07-28 11:46:41.925 Nanny[1445:11303] serviceId:
2014-07-28 11:46:41.925 Nanny[1445:11303] sender:
2014-07-28 11:46:41.925 Nanny[1445:11303] hasPair:
Thank you.
in NSLog, you're not passing type of arguments. Try this
if (obj) {
NSAssert([obj isKindOfClass:[NSDictionary class]], #"Expected a dictionary");
NSNumber *code = obj[#"code"];
NSLog(#"code: %#", code);
NSString *serviceId = obj[#"serviceID"];
NSLog(#"serviceId: %#", serviceId);
NSNumber *sender = obj[#"sender"];
NSLog(#"sender: %#",sender);
NSNumber *hasPair = obj[#"hasPair"];
NSLog(#"hasPair: %#", hasPair);
} else {
NSLog(#"Failed to parse JSON: %#", [error localizedDescription]);
}
I am new in the iOS development and i am calling the web service that returns me data like
[
{
"ID": "3416a75f4cea9109507cacd8e2f2aefc3416a75f4cea9109507cacd8e2f2aefc",
"Name": "2M Enerji"
},
{
"ID": "072b030ba126b2f4b2374f342be9ed44072b030ba126b2f4b2374f342be9ed44",
"Name": "Çedaş"
},
{
"ID": "093f65e080a295f8076b1c5722a46aa2093f65e080a295f8076b1c5722a46aa2",
"Name": "Çelikler"
},
{
"ID": "7cbbc409ec990f19c78c75bd1e06f2157cbbc409ec990f19c78c75bd1e06f215",
"Name": "Çoruh EDAŞ"
},
{
"ID": "70efdf2ec9b086079795c442636b55fb70efdf2ec9b086079795c442636b55fb",
"Name": "İçdaş"
}
]
Now i am trying to get it in the array , the array will be seperate for the name and id , i am done till taking in NSDICT following is my code
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"finish loading");
NSString *loginStatus = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
NSString *responsewith = [[NSString alloc] initWithData:webData
encoding:NSUTF8StringEncoding];
//providerData = [NSKeyedUnarchiver unarchiveObjectWithData:webData];
providerDropData = [NSString stringWithFormat:responsewith];
NSLog(#"drop %#",providerDropData);
NSArray *providerData = [providerDropData valueForKey:#"ID"];
NSLog(#"jey %#",responsewith);
NSLog(#"resonser %#",responsewith);
NSLog(#"laoding data %#",loginStatus);
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
When i tried saving the NSDictionary to the NSArray for #"ID" the application get crashed.
Please help
You simply want to use NSJSONSerialization
NSError *error = nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
if (!results)
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
// get the first provider id
NSString *providerData = results[0][#"ID"];
You can fetch data from JSON like below way as well,
id jsonObjectData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
if(jsonObjectData){
NSMutableArray *idArray = [jsonObjectData mutableArrayValueForKeyPath:#"ID"];
NSMutableArray *nameArray = [jsonObjectData mutableArrayValueForKeyPath:#"Name"];
}
Convert the data to NSDictionary by parsing, then you can extract using KVP.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSDictionary * providerDropData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
NSLog(#"drop %#",providerDropData);
NSMutableArray *providerData = [NSMutableArray new];
NSString *key = #"ID";
for (key in providerDropData){
NSLog(#"Key: %#, Value %#", key, [providerDropData objectForKey: key]);
[providerData addObject:[providerDropData objectForKey:key]];
}
NSLog("ID Array = %#", providerData]);
}
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;