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]);
}
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"];
I have a JSON like below (getting from an URL)-
{
action :getAllJournal;
data :{
journalList :[{
cancelled : F;
"cust_code" : "700-T022";
"journal_amount" : 2216;
"journal_code" : "JV1603/001";
"journal_date" : "2016-03-15 00:00:00";
"journal_id" : 1;
outstanding : 0;
},
{
cancelled : F;
"cust_code" : "700-0380";
"journal_amount" : 120;
"journal_code" : "JV1605/006";
"journal_date" : "2016-05-31 00:00:00";
"journal_id" : 2;
outstanding : 120;
},
{
cancelled : F;
"cust_code" : "700-T280";
"journal_amount" : 57;
"journal_code" : "JV1609/001";
"journal_date" : "2016-09-22 00:00:00";
"journal_id" : 3;
outstanding : 0;
}
];
};
message = "";
"message_code" = "";
result = 1;}
The code below doing is getting the JSON from URL and storing them in NSMutableArray. Until storing them into array, it's working fine but I'm bit confused with the JSON format and don't know how to get result by a key.
__block NSMutableArray *jsonArray = nil;
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
if(![[jsonObject objectForKey:#"journalList"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"journalList"];
NSLog(#"array: %lu",(unsigned long)array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"journalList"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"cust_code - journal_amount : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"cust_code"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"journal_amount"]]);
}
}
}else{
NSLog(#"Error - %#",jsonError);
}
}
}];
From this, I am able to get the JSON successfully. But it's always giving me this error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in an object around character 6." UserInfo={NSDebugDescription=No string key for value in an object around character 6.} How can I get all values from journalList? I'm new to iOS, that's why not sure what I'm missing.
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
jsonArray = (NSMutableArray *)myJSON;
NSString *nsstring = [jsonArray description];
NSLog(#"IN STRING -> %#",nsstring);
NSData *data = [nsstring dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
I'd say: NO and NO.
I wouldn't do a #try/#catch on a NSJSONSerialization, because the real issues are on the error parameter (and they won't throw a NSException for most of the cases). Just check if (data) is quite efficient.
Then, let's say it worked, and you have myJSON.
In fact, myJSON is a NSDictionary, not a NSArray, so the cast is useless and doesn't make sense.
Next issue:
Your are using -description (okay, if you want to debug), but you CAN'T use it to reconstruct AGAIN a JSON. It's not a valid JSON, it's the way the compiler "print" an object, it adds ";", etc.
If your print [nsstring dataUsingEncoding:NSUTF8StringEncoding] and data you'll see that they aren't the same.
For a more readable:
NSString *dataJSONStr = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];, it's clearly not the same structure as your nsstring.
Then, you are redoing the JSON serialization? Why ?
So:
NSError *errorJSON = nil;
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorJSON];
if (errorJSON)
{
NSLog(#"Oops error JSON: %#", errorJSON);
}
NSDictionary *data = myJSON[#"data"];
NSArray *journalList = data[#"journalList"]
for (NSDictionary *aJournalDict in journalList)
{
NSUInteger amount = [aJournalDict[#"journal_amount"] integerValue];
NSString *code = aJournalDict[#"journal_code"];
}
There is a dictionary named "data" you're not fetching, represented by {}.
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (!jsonError) {
// Fetch the journalList
NSArray *journalList = json[#"data"][#"journalList"];
// iterate over every entry and output the wanted values
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"cust_code"], journal[#"journal_amount"]);
}
}
json[#"key"] is a short form of [json objectForKey:#"key"] I find easier to read.
That is not a valid JSON. Entries should be separated by comma ,, not semicolon ;
You need to fetch journalList from data.
Try below code:
This is demo code to create array like you:
NSMutableDictionary *jsonObject = [NSMutableDictionary new];
jsonObject[#"action"]= #"";
jsonObject[#"message"]= #"";
jsonObject[#"message_code"]= #"";
jsonObject[#"result"]= #"1";
NSMutableArray *ary1 = [NSMutableArray new];
for(int i=0;i<5;i++)
{
NSMutableDictionary *dd = [NSMutableDictionary new];
dd[#"cancelled"]= #"F";
dd[#"cust_code"]= #"F";
[ary1 addObject:dd];
}
NSMutableDictionary *dicjournal = [NSMutableDictionary new];
[dicjournal setObject:ary1 forKey:#"journalList"];
[jsonObject setObject:dicjournal forKey:#"data"];
This is main Logic:
NSMutableArray *journalList = [NSMutableArray new];
NSMutableDictionary *dic = [jsonObject valueForKey:#"data"];
journalList = [[dic objectForKey:#"journalList"] mutableCopy];
Looks like your JSON is invalid. You can see whether your JSON is correct or not using http://jsonviewer.stack.hu/ and moreover format it. Meanwhile your code is not using "data" key to fetch "journalList" array.
Code : -
NSDictionary *dic = [jsonObject valueForKey:#"data"];
NSMutableArray *arr = [dic objectForKey:#"journalList"];
for (int index=0 ; index < arr.count ; index++){
NSDictionary *obj = [arr objectAtIndex:index];
// Now use object for key from this obj to get particular key
}
Thanks #Larme and #Amset for the help. I was doing wrong the in the NSMutableArray part. The correct version of this code is in the below:
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *urlString = [NSString stringWithFormat:#"http://xxxxxxx/api.php?action=getAllJournal"];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError)
{
if (data)
{
id myJSON;
#try {
myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
}
#catch (NSException *exception) {
}
#finally {
}
NSArray *journalList = myJSON[#"data"][#"journalList"];
for (NSDictionary *journal in journalList) {
NSLog(#"%# %#", journal[#"journal_date"], journal[#"journal_amount"]);
}
}
}];
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"];
I need to display particular object for key(currency) using post method after getting response from web.
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController{
NSMutableData *mutableData;
NSMutableString *arr;
#define URL #"website"
// change this URL
#define NO_CONNECTION #"No Connection"
#define NO_VALUES #"Please enter parameter values"
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
-(IBAction)sendDataUsingPost:(id)sender{
[self sendDataToServer :#"POST"];
}
-(IBAction)sendDataUsingGet:(id)sender{
[self sendDataToServer : #"GET"];
}
-(void) sendDataToServer : (NSString *) method{
NSString *Branchid=#"3";
serverResponse.text = #"Getting response from server...";
NSURL *url = nil;
NSMutableURLRequest *request = nil;
if([method isEqualToString:#"GET"]){
NSString *getURL = [NSString stringWithFormat:#"%#?branch_id=%#", URL, Branchid];
url = [NSURL URLWithString: getURL];
request = [NSMutableURLRequest requestWithURL:url];
NSLog(#"%#",getURL);
}else{ // POST
NSString *parameter = [NSString stringWithFormat:#"branch_id=%#",Branchid];
NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
url = [NSURL URLWithString: URL];
NSLog(#"%#", parameterData);
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:parameterData];
arr= [NSMutableString stringWithUTF8String:[parameterData bytes]];
NSLog(#"responseData: %#", arr);
//NSLog(#"%#",[[arr valueForKey:#"BranchByList"]objectForKey:#"currency"]);
}
[request setHTTPMethod:method];
[request addValue: #"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
if( connection )
{
mutableData = [NSMutableData new];
//NSLog(#"%#",[connection valueForKeyPath:#"BranchByList.currency"]);
}
}
-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
serverResponse.text = NO_CONNECTION;
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
//NSLog(#"Response from Server : %#", responseStringWithEncoded);
NSLog(#"%#",responseStringWithEncoded );
NSLog(#"%#",[responseStringWithEncoded valueForKeyPath:#"BranchByList.currency"] );
NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
serverResponse.attributedText = attrStr;
// NSLog(#"%#",attrStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
i got response branch_id=3 but i want to show to "currency" but i tried lot but failure.
my response like this I need to display only currency.....
Response from Server :
{"BranchByList":
[
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
},
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24"
}
]};
Your response structure is:
-Dictionary
--Array
---Dictionary Objects
You need to convert your Data into NSDictionary to parse it.
Following code will do that for you:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData
options:kNilOptions
error:&error]; //Now we got top level dictionary
NSArray* responseArray = [json objectForKey:#"BranchByList"]; //Now we got mid level response array
//Get Embeded objects from response Array:
NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for
NSString *buyingPrice = [priceDic objectForKey: #"buy"]; //Buying price
NSString *sellingPrice = [priceDic objectForKey:#"sell"]; //Selling price
NSString *currency = [priceDic objectForKey:#"currency"]; //Currency
Though this is only sticking to the point and getting the job done.
Proper way to get the job done would be to create a model class for response. Create a class inherited from NSObject and use it as model for this response. Add a initWithDic: method to that class, Pass it your response dic as parameter and delegate all this dictionary parsing to that method.
Also, NSURLConnection is deprecated since iOS 9.0. You should use NSURLSession instead.
Try This May be it will help you:-
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMArray *array1 = [dict6 objectForKey:#"BranchByList"];
NSLog(#"DICT : %#",array1);
NSDictionary *Dict3 = [array1 objectAtIndex:0];
NSString *Str1 = [dict3 objectForKey:#"currency"];
NSLog(#"Str1 : %#",Str1);
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
} else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
} else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
} else
{
return jsonObject;
}
}
I am trying to get Dictionary form json, but the following code dosent seem to work. I am getting the JSON, but cannot get the dictionary from it.
NSString *str = [[NSMutableString alloc] initWithData:responseCust encoding:NSUTF8StringEncoding];
NSLog(#"CUSTOMER string -----################ %#", str);
if(str.length>5)
{
SBJSON *jsonparser=[[SBJSON alloc]init];
NSDictionary *res= [jsonparser objectWithString:str];
NSLog(#"Contants Results %#",res);
[jsonparser release];
[str release];
}
Thank You.
Please Follow the below code
NSURL * url=[NSURL URLWithString:str];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
//Get json data in Dictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
try this one..
Use NSJSONSerialization and make use of
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error to convert JSON to foundation object.
hope this helps
Just try to Either
NSDictionary *dict = [str JSONValue];
NSLog(#"%#", dict);
OR
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseCust options:nil error:&error];
NSLog(#"%#", dict);
+(NSDictionary *)converJsonStringToDictionary:(NSString *)jsonString
{
NSString *stringToConvert = jsonString;
if (![self isObjectEmpty:stringToConvert]) {
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *convertedData = nil;
convertedData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (error != nil){
DLog(#"Error converting jsonString to dictionary: %#", [error description]);
convertedData = nil;
}
else if ([convertedData isKindOfClass:[NSDictionary class]]) {
DLog(#"The converted data is of kind NSDictionary");
}
else if ([convertedData isKindOfClass:[NSArray class]]){
DLog(#"The converted data is of kind NSArray");
convertedData = nil;
}
else{
DLog(#"The converted data is not NSDictionary/NSArray");
convertedData = nil;
}
return convertedData;
}
else{
DLog(#"The received jsonString is nil")
return nil;
}
}
Here, try adding the encoding...
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
NSLog(#"dict: %#", jsonDict);
Check here for some samples on how to handle json on objective-c