IOS: Dictionary Return null value/Data - ios

in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)

Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];

There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).

Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];

Related

IOS: getting values in an array from dictionary

In my project i have an array which contains multiple dictionaries with some key values each. I want to get the all the value of "Link" key into an NSMutableArray.
the current array which contain dictionary is in the form of:
(
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
link = "https://player.vimeo.com/video/26186155";
title = "Cervical Spine Medial Branch Nerve Neurolysis neurosurgical animations";
};
},
{
YoutubeVideo = {
description = "What is endoscopic brain surgery";
link = "https://player.vimeo.com/video/16144037";
title = "What is endoscopic brain surgery";
};
},
{
YoutubeVideo = {
description = "Cervical Spine Medial Branch Nerve Block Injection pain management";
link = "https://player.vimeo.com/video/26186167";
title = "Cervical Spine Medial Branch Nerve Block Injection pain management";
};
},
{
YoutubeVideo = {
description = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
link = "https://player.vimeo.com/video/54275902";
title = "Seguiremos - Hospital Sant Joan de D\U00e9u y Macaco";
};
},
{
YoutubeVideo = {
description = "Basic Shoulder Arthroscopy in Orthopaedics";
link = "https://www.youtube.com/embed/ywBVWIzGxtw";
title = "Basic Shoulder Arthroscopy in Orthopaedics";
};
}
i want to get all the values of link into a single array.
Currently the code i use which gives the following output is:
-(void)videolisting
{
NSString *post = #"api_key=bf45c093e542f057c123ae7d6";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://hChe/api/video"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
//NSLog(#"str : %#",dict6);
vidnamearray = [dict6 objectForKey:#"video"];
NSLog(#" Required Dir: %#",vidnamearray);
}
Try below solution
NSMutableArray *subArray=[[NSMutableArray alloc]init];
for(NSDictionary *dict in vidnamearray)
{
NSDictionary *subDict=[dict valueForKey:#"YoutubeVideo"];
[subArray addObject:[subDict valueForKey:#"link"]];
}
subArray will get all the values in the link key..!
Hope it helps you.....!
Try this
yourArr.valueForKeyPath("YoutubeVideo.link")
This will give the array containing all links.

Create JSON string in iOS

How to create JSON string for HTTP Request in iOS
i have these values:
{"name":"customer6","pass":"customer6", "mail":"customer6#xy.com","user_roles":"5", "field_login_pin_value":{"und":[{"value":"2324"}]} }
So how to make JSON string out of this data ?
Here is my code :
NSArray *keys = [NSArray arrayWithObjects:#"name",#"pass",#"mail",#"user_roles",#"field_login_pin_value", nil];
NSArray *objects = [NSArray arrayWithObjects:#"customer6",#"customer6",#"customer6#xy.com",#"5",#"{\"und\":[{\"value\":\"2324\"}]", nil];
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSString *jsonString = [jsonDictionary JSONRepresentation];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://xxxxxxxx/register.json"]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:jsonData];
nsconnection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
When I hit the web-service request, I get the following response:
"form_errors" = {
"field_login_pin_value][und][0][value" = "PIN value field is required.";
};
}
I always get the same error
Can anyone let me know what is wrong with my implementation ?
I'd imagine that JSONRepresentation is formatting "{\"und\":[{\"value\":\"2324\"}]" as the literal string it is, not as a value within a dictionary within an array within a dictionary. You should make the whole dict-array-dict structure. This will all be easier if you use array and dictionary literals:
NSDictionary *jsonDictionary = #{
#"name" : #"customer6",
#"pass" : #"customer6",
#"mail" : #"customer6#xy.com",
#"user_roles" : #"5",
#"field_login_pin_value" : #{
#"und":#[
#{
#"value" : #"2324"
}
]
}
};
You can, of course, coalesce the pin_value value to a single line, this is just for clarity.

Convert NSData (retrieved from wcf ) to NSArray

I want to convert NSData, which I get it by accessing web service, to NSArray. How can I do it?
Here is the structure that I want to convert from NSData:
NSArray:
NSDictionary1 : roomName departmentName
NSDictionary2 : roomName departmentName
NSDictionary3 : roomName departmentName
NSDictionary4 : roomName departmentName
NSDictionary5 : roomName departmentName
...
GetRoomList method of the web service returns a list. The structure of the list is above. Code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *soapMessage = [NSString stringWithFormat:#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><m:GetRoomList xmlns:m=\"http://http://portNumber/ilacDirektif.svc/\"><departId xsi:type=\"xsd:int\">0</departId><roomId xsi:type=\"xsd:int\">0</roomId></m:GetRoomList></SOAP-ENV:Body></SOAP-ENV:Envelope>"];
NSURL *url=[NSURL URLWithString:#"http://port number/ilacDirektif.svc/"];
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/ilacDirektif.svc" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"port number" forHTTPHeaderField:#"Host"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse* response = nil;
NSData *data =[NSURLConnection sendSynchronousRequest: theRequest returningResponse: &response error: nil];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:data];
if(array){NSLog(#"%#",array); }else{ NSLog(#"Failed"); }
if (data) {NSLog(#"%#",data);} else { NSLog(#"Failed");}
}
Error:
2013-05-31 09:59:45.208 IlacOrder[18513:11303] -[__NSCFData getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860 2013-05-31 09:59:45.222 IlacOrder[18513:11303] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFData
getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860'
* First throw call stack: (0x1c8e012 0x10cbe7e 0x1d194bd 0x1c7dbbc 0x1c7d94e 0xacc7b4 0xacc762 0xafac85 0xb22c7a 0x2a55 0xf4817 0xf4882
0xf4b2a 0x10bef5 0x10bfdb 0x10c286 0x10c381 0x10ceab 0x10d4a3 0x10d098
0x2460 0x10df705 0x16920 0x168b8 0xd7671 0xd7bcf 0xd6d38 0x4633f
0x46552 0x243aa 0x15cf8 0x1be9df9 0x1be9ad0 0x1c03bf5 0x1c03962
0x1c34bb6 0x1c33f44 0x1c33e1b 0x1be87e3 0x1be8668 0x1365c 0x1ded
0x1d15 0x1) libc++abi.dylib: terminate called throwing an exception
The function in .svc:
public List<DepartmentRoom>GetRoomList(int roomId,int departId()){
return manager.GetRoomList(roomId,departId);
}
GetRoomList:
public List<DepartmentRoom> GetRoomList(int departId,int roomId){
var cmd = OracleHelper.GetOracleCommand(_conn, StoredProcedure.Procedure1);
if (_conn.State == ConnectionState.Closed)
_conn.Open();
OracleCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["P_DEPARTID"].Value = departId;
cmd.Parameters["P_ROOMID"].Value = roomId;
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
object o = cmd.Parameters["P_REF"].Value;
var roomList = new List<DepartmentRoom>();
while (dr.Read())
{
var departmentRoom = new DepartmentRoom
{
DepartId = Convert.ToInt32(dr["DEPARTID"]),
DepartmentName = dr["DEPART"].ToString(),
RoomId = Convert.ToInt32(dr["ROOMID"]),
RoomName = dr["ROOM"].ToString()
};
roomList.Add(departmentRoom);
}
return roomList;
}
Perhaps it would be worth reading the documentation of the methods and classes you are trying to use. unarchiveObjectWithFile: takes a file path as its argument, not an NSData. Finding the method in the docs that takes an NSData as its input is left to you as an exercise.
This worked for me:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:REQIP]];
NSData *myPostData = [[NSString stringWithFormat:#"{\"departId\":%d,\"roomId\":%d}",departId,roomId] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[request setPostBody:myMutablePostData];
[request setRequestMethod:#"GET"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startSynchronous];
NSMutableArray *list =[[NSMutableArray alloc]init];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:[[request responseString]dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingMutableContainers error:nil ];
for(NSDictionary *theItem in [jsonObjects objectForKey:#"RequestMethodResult"]){
[list addObject:[[ClassModel alloc]initWithDictionary:theItem]];
}
return list;
ClassModel is the structure of the Dictionary that each object item of NSMutableArray is.

NSJSONSerialization data in a different format

I am using Parse.com as a backend of my application, where I am currently storing the data there.
The data is a list of video game consoles. I was able to make an output of it, but instead of JSON data, the output is a big NSMutableArray.
This is my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSError *error;
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"The list: %#", listOfConsoles);
}
The output:
The list: {
results = (
{
createdAt = "2013-03-21T07:26:04.149Z";
name = PlayStation;
objectId = vloIK0MZIA;
updatedAt = "2013-03-21T07:26:04.149Z";
},
{
createdAt = "2013-03-21T07:26:34.209Z";
name = Wii;
objectId = RIRpgbznlq;
updatedAt = "2013-03-21T07:26:34.209Z";
},
{
createdAt = "2013-03-21T07:26:39.391Z";
name = Xbox;
objectId = xBNgHtJbrV;
updatedAt = "2013-03-21T07:26:39.391Z";
}
);
}
What I want the output to be:
{
"results" : [
{
"objectId" : "vloIK0MZIA",
"updatedAt" : "2013-03-21T07:26:04.149Z",
"createdAt" : "2013-03-21T07:26:04.149Z",
"name" : "PlayStation"
},
{
"objectId" : "RIRpgbznlq",
"updatedAt" : "2013-03-21T07:26:34.209Z",
"createdAt" : "2013-03-21T07:26:34.209Z",
"name" : "Wii"
},
{
"objectId" : "xBNgHtJbrV",
"updatedAt" : "2013-03-21T07:26:39.391Z",
"createdAt" : "2013-03-21T07:26:39.391Z",
"name" : "Xbox"
}
]
}
BY THE WAY
Why is it that when I have a separate NSData in the code:
NSData *JSONData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
And change my NSJSONSerialization to:
id listOfConsoles = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:&error];
The output will be:
The list: {
error = unauthorized;
}
The first list is a NSDictionary with a single key called "results" which has an NSArray of NSDictionaries.
The second list is the same thing..
Edit 1.0:
Just to clarify, the second output is JSON, ok? Simply as that, just check here and validate yourself. The first one is the outputted JSON that is inside an NSObject. Of course there will be slight differences...
Your Authentication not done successfully. Please check APPLICATION_ID and REST_API_KEY values.
I was an idiot. I never realized that I tried to convert the JSON to something else, when I wanted the JSON data.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:#"https://api.parse.com/1/classes/Consoles"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"APPLICATION_ID" forHTTPHeaderField:#"X-Parse-Application-Id"];
[request setValue:#"REST_API_KEY" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
NSString *listOfConsoles = [[NSString alloc] initWithData:[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"%#", listOfConsoles);
}

Web service method not hit when called via Objective C

My App_Code/IGetEmployees.vb file
<ServiceContract()> _
Public Interface IGetEmployees
<OperationContract()> _
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="json/contactoptions")> _
Function GetAllContactsMethod(strCustomerID As String) As List(Of NContactNames)
End Interface
My App_Code/GetEmployees.vb file
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetAllContactsMethod(strCustomerID As String) As List(Of NContactNames) Implements IGetEmployees.GetAllContactsMethod
Utilities.log("Hit get all contacts at 56")
Dim intCustomerID As Integer = Convert.ToInt32(strCustomerID)
Dim lstContactNames As New List(Of NContactNames)
'I add some contacts to the list.
Utilities.log("returning the lst count of " & lstContactNames.Count)
Return lstContactNames
End Function
NContactNames is a class with 3 properties.
So i am using ASP.NET web services to retrieve information from SQL server and pass it to my iPad in JSON format. I have a problem with parameter passing. So like you see i have 2 files IGetEmployees.vb and GetEmployees.vb. I am implementing the method GetAllContactsMethod. What's happening is the two lines in GetEmployees.vb file (Utilities.log), they never get logged. The function is not getting called at all.
My objective c code to call this function
NSString *param = [NSString stringWithFormat:#"strCustomerID=%#",strCustomerID];
jUrlString = [NSString stringWithFormat:#"%#",#"http://xyz-dev.com/GetEmployees.svc/json/contactoptions"];
jurl = [NSURL URLWithString:jUrlString];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:jurl];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#" request string is %#",[[request URL] absoluteString]);
NSLog(#"Done");
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
jData = [NSMutableData data];
NSError *jError;
NSMutableDictionary *json =[NSJSONSerialization JSONObjectWithData:jData options:kNilOptions error:&jError];
NSLog(#"%#",json); //Gets Here and prints (null)
NSLog(#"Done"); //prints this as well.
}
else
{
NSLog(#"No");
}
At the time of posting this code the "if" statement is true and (null) is printed followed by "Done"
The output of my absolute request is:
request string is http://xyz-dev.com/GetEmployees.svc/json/contactoptions
This is the first time i am writing json to accept parameters. So i might be missing something.What is it?Why is the function not getting called at all on the Visual Studio side. If you need more info please ask.Thanks...
this is the moethod in Objetive-C, for that.
-(void) insertEmployeeMethod
{
if(firstname.text.length && lastname.text.length && salary.text.length)
{
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
NSURL *WcfSeviceURL = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:WcfSeviceURL];
[request setHTTPMethod:#"POST"];
// connect to the web
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:respData
options:NSJSONReadingMutableContainers
error:&error];
NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:#"InsertEmployeeMethodResult"];
//create some label field to display status
status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:#"Inserted %#, %#",firstname.text,lastname.text]:[NSString stringWithFormat:#"Failed to insert %#, %#",firstname.text,lastname.text];
}
}
Before to run the code, test your URL with POSTMAN, is an app from Google Chrome.
regards.

Resources