I am trying to parse json response(which I get from result tag of a SOAP webservice response) as shown in pictures with following lines.
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetPhotoSession xmlns=\"http://tempuri.org/\">"
"<UserID>%#</UserID>"
"<photoSessionID>%#</photoSessionID>"
"</GetPhotoSession>"
"</soap:Body>"
"</soap:Envelope>",[HelperClass retrieveStringForKey:kUserID],self.currentSession.sessionID];
NSURL *url = [NSURL URLWithString:kBaseURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/GetPhotoSession" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection ) {
self.webResponseData = [NSMutableData data];
}else {
NSLog(#"Some error occurred in Connection");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.webResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.webResponseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Some error in your Connection. Please try again.");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Received Bytes from server: %d", [self.webResponseData length]);
NSString *myXMLResponse = [[NSString alloc] initWithBytes: [self.webResponseData bytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",myXMLResponse);
NSError *errorPointer;
NSDictionary *dict = [XMLReader dictionaryForXMLString:myXMLResponse error:&errorPointer];
NSString *jsonData = dict[#"soap:Envelope"][#"soap:Body"][#"GetPhotoSessionResponse"][#"GetPhotoSessionResult"][#"text"];
NSData *data = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorPointer];
NSLog(#"%#",[json objectForKey:#"Head"]);
}
But I am getting nil in "json" object. Here is the pastie link for JSON response http://pastie.org/9799331. Following is the description of error pointer.
Printing description of errorPointer:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7d0156a0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Is this your own web service or an existing one? If this is your own, are you sure your JSON is actually correct?
I believe the problem is here:
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah ==
"
Note the key point here. That the closing double quote is on the next line. It should be
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah =="
For future reference, it is far easier if you cut and paste the JSON payload text in your question versus showing an image.
So grabbing your data from here:
http://pastie.org/9799331#2,22,482
I have run it through this code:
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:#"badjson" ofType:#"txt"];
NSString *jsonStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#""];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"Error is %#", error);
NSLog(#"JSON is %#", json);
Note that I have one commented out line right now. When I do this, it fails. However the failure is different than what you listed above. I get.
Error is Error Domain=NSCocoaErrorDomain Code=3840 "The operation
couldn’t be completed. (Cocoa error 3840.)" (Unescaped control
character around character 120.) UserInfo=0x7f9519f71510
{NSDebugDescription=Unescaped control character around character 120.}
If I uncomment out that line, then it works. Only showing a snippet of the output:
2014-12-26 12:03:35.020 Sample[49732:6379864] Error is (null)
2014-12-26 12:03:35.022 Sample[49732:6379864] JSON is {
Head = (
{
ID = 1092;
ImageBase64Data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACAWGBwYFCAcGhwkIiAmMFA0MCwsMGJGSjpQdGZ6eHJmcG6AkLicgIiuim5woNqirr7EztDOfJri8uDI8LjKzsb/
Your data is using an base64 output which uses newlines to delimit each encoded line. This is why you see at the end the text that looks like:
==
","ImageName"
You'll also notice the vast majority of lines in the Base64 look uniform .. because of this delimiting.
Strip out the newlines using this (you need to modify it for you code)
jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#""];
If that doesn't work, then you need to provide some more info:
-Is the output taken from Xcode console?
-Add in your code where the NSLog exists to get the output (if you don't have it, then please add one).
-Once you add the NSLog, provide that output
While it may seem like you've "already provided that info", there is obviously a gap in information. Else I would expect to see the same NSError output. So we're either missing steps, or maybe there is some other variance. For example, I'm running this in an iOS 8 simulator. Not that it should matter too much, but there is always a possibility that you're running on an older version of iOS that parses the JSON differently.
Related
below code i use an asmx webservice to get a file as byte array and want to save it to iphone application's documents directory
the file i request is a sqlite file
and my code is :
-(void)getfile{
NSString* soapMessage = [NSString stringWithFormat:
#"<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> <GetDocument xmlns=\"http://tempuri.org\"> <DocumentName>%#</DocumentName> </GetDocument></soap:Body> </soap:Envelope>", #"ErtugrulGuler"];
NSURL* theUrl = [NSURL URLWithString:#"http://test.xxxx.com/xxxxx/xxxx.asmx"];
NSString* msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
NSMutableURLRequest* theRequest = [NSMutableURLRequest requestWithURL:theUrl];
[theRequest addValue:#"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue:#"http://tempuri.org/GetDocument" forHTTPHeaderField:#"SOAPAction"];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connect = [[NSURLConnection alloc] initWithRequest: theRequest delegate:self];
if (connect)
{
}
else {
NSLog(#"No Connection established");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
downloadData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[downloadData appendData:data];
NSString *receivedDataString = [[NSString alloc] initWithData:downloadData encoding:NSUTF8StringEncoding];
NSLog(#"data string: %#",receivedDataString);
NSLog(#"data length: %d",[data length]);
//NSLog(#"bytesWritten == %d error == %#",bytesWritten,[fileOutputStream streamError]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
//NSLog(#"finish loading");
[self performSelector:#selector(downloadData:) withObject:downloadData afterDelay:0];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
}
-(void)downloadData:(NSData*)response
{
//NSLog(#" \n\n STRING = %# \n\n ",[[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding]);
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir=[paths objectAtIndex:0];
NSString *documentFile=[documentDir stringByAppendingPathComponent:#"abc.sqlite"];
NSString * yourAppendingText=[[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding];
[yourAppendingText writeToFile:documentFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
and this is my webservice method that returns byte array
[WebMethod]
public Byte[] GetDocument(string DocumentName)
{
string strdocPath;
strdocPath = "path" + DocumentName;
FileStream objfilestream = new FileStream(strdocPath,FileMode.Open,FileAccess.Read);
int len = (int)objfilestream.Length;
Byte[] documentcontents = new Byte[len];
objfilestream.Read(documentcontents,0,len);
objfilestream.Close();
return documentcontents;
}
this code connects successfully but i dont know how to get file with NSData and write the file to Documents Directory as .sqlite
#EDIT:
i solve something but the file i wanted to get is 53kb and my recieved data as string like :
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetDocumentResponse xmlns="http://tempuri.org/" /></soap:Body></soap:Envelope>
and data length : 297 so it cannot get the data i think
in asp.net i run the service and get data successfully. so there is no problem with service but maybe maxiimumrecieving size for ios could be increased? but how?
NSOutputStream *fileOutputStream;
NSString *databasePath = [NSString stringWithFormat:#"%#/Documents/%#",NSHomeDirectory(),#"database.sqlite"];
fileOutputStream = nil;
fileOutputStream = [[NSOutputStream alloc] initToFileAtPath:databasePath append:NO];
[fileOutputStream open];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
int bytesWritten = [fileOutputStream write:[data bytes] maxLength:[data length]];
NSLog(#" %s bytesWritten == %d error == %#",__FUNCTION__,bytesWritten,[fileOutputStream streamError]);
}
I have the following code to get data from server;
-(void)loginForFaceBook
{
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:#"https://www.googleapis.com/auth/plus.me"
clientID:#"27615...6qdi60qjmachs.apps.googleusercontent.com"
clientSecret:#"Fs8A...u2PH"
keychainItemName:#"OAuth2 Sample:
Google+"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[[self navigationController] pushViewController:viewController
animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; //
kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
// NSString *str = [[NSString alloc] initWithData:responseData
// encoding:NSUTF8StringEncoding];
// NSLog(#"%#", str);
}
// self.auth = nil;
} else {
// NSString *authCode = [NSString alloc]in;
NSMutableURLRequest * request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/tokens"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
NSLog(#"%#",auth);
NSLog(#"ho gya success %# :::: %# :::: %#", auth.accessToken,
auth.refreshToken, auth.code);
NSMutableURLRequest * response;
NSError * error;
request.URL = [NSURL URLWithString:#"http://api.kliqmobile.com/v1/tokens"];
NSString *post = [NSString stringWithFormat:#"
{\"token\":\"%#\",\"secret\":\"%#\",\"service\":\"%#\",\"handle\":\"%#\"}",
auth.accessToken,auth.code,#"google",nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
error = nil;
response = nil;
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
delegate:self];
[connection start];
}
I have implemented the NSURLConnection delegtes method and data is printing well like this
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSMutableURLRequest * response;
NSError * error;
NSLog(#"Did Receive Data %#", [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding]);
NSMutableURLRequest * requestContacts;
requestContacts = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/contacts"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
[requestContacts setHTTPMethod:#"GET"];
[requestContacts setAllHTTPHeaderFields:headers];
error = nil;
response = nil;
NSData* data1 = [NSURLConnection sendSynchronousRequest:requestContacts
returningResponse:&response error:&error];
NSLog(#"WE GET THE REQUIRED TOKAN DATA %# :: %# :: %#", [[NSString alloc]
initWithData:data1 encoding: NSASCIIStringEncoding], error ,response);
}
but after that my app get crashed and it is giving following error;
[NSHTTPURLResponse release]: message sent to deallocated instance 0xcb51070.
please suggest me how to do this.
A couple of thoughts:
What is the intent of your didReceiveData method? There are a bunch of issues here:
You really shouldn't be doing a synchronous network request in the middle of a NSURLConnectionDataDelegate method.
You shouldn't be doing synchronous requests at all, but rather do them asynchronously.
What is the connection between receiving data and your creation of this new request? You're not using the data in the request, so why do it here?
The typical pattern is:
The didReceiveResponse should instantiate a NSMutableData object in some class property.
The only function of didReceiveData should be to append the received data to the NSMutableData. Note, this method may be called multiple times before all the data is received.
In connectionDidFinishLoading, you should initiate any next steps that you take upon successful completion of the request. If you wanted to do start another asynchronous network request when the initial request is done, do that here.
In didFailWithError, you obviously handle any failure of the connection.
When you call connectionWithRequest, you should not use the start method. Only use start when you use initWithRequest:delegate:startImmediately: with NO for the startImmediately parameter. Otherwise the connection starts automatically for you and you're only starting it a second time.
Unrelated to your original question, but your creation of post string cannot be right. You're missing a parameter value. Even better, rather than creating JSON manually, use NSDictionary and then use NSJSONSerialization to make the NSData object containing the JSON from this dictionary. That's much safer:
NSDictionary *params = #{#"token" : auth.accessToken,
#"secret" : auth.code,
#"service" : #"google",
#"handle" : #""};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
Clearly, supply whatever you need for the handle value.
A tangential process-related observation, but I'm wondering if you're taking advantage of everything Xcode offers. For example, your declaration of response as a NSMutableURLRequest but then using that as a parameter to sendSynchronousRequest should have generated a compiler warning. The same thing is true with your stringWithFormat for your post string (my third point). That should have generated a warning, too.
Neither of these are immediately relevant, but I wonder if you are failing to heed any other compile-time warnings. These warnings are your best friend when writing robust code and I would recommend resolving all of them. To go a step further, you should also run the project through the static analyzer ("Analyze" on "Product" menu, or shift+command+B), and resolve anything it points out, too.
FIRST EDIT:
I put returnData in JSONObjectWithData:options:error but the error persists.
The problem happens 1 in 10 times, but it's annoying because the application does not work.
2014-02-18 10:26:03.236 finalAbogados[47279:f803] Error en consulta basica: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x686c330 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
im doing an APP on iOS that get a JSON object from a PHP Script.
The script calls data from data base in MS SQL and encode these data in a JSON Object. Then i get the object on iOS and i use NSJSONSerialize for handle data.
The problem is, sometimes I get a null value and sometimes I get the array correctly. The data returned me the script is always the same, expose here:
[{"0":"","NombreOrganismo":"","1":"Judicial","NombreTipoInstancia":"Judicial","2":"(Sin asignar)","Numero":"(Sin asignar)"}]
The code that performs the query and the data in question is:
NSString *myRequestString = [NSString stringWithFormat:#"user=%#&pass=%#&cod_asunto=%#", u_received, p_received, cod_received];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:#""]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:myRequestData];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata options:kNilOptions error:&jsonError];
NSMutableArray *NombreOrga = [[NSMutableArray alloc] init];
NSMutableArray *NombreInstancia = [[NSMutableArray alloc] init];
NSMutableArray *Numero = [[NSMutableArray alloc] init];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"Its an ARRAY!!.");
NSArray *jsonArray = (NSArray *)jsonObject;
for (id item in jsonArray) {
if ([item isKindOfClass:[NSDictionary class]]) {
NSString *aux = [(NSDictionary*)item objectForKey:#"NombreOrganismo"];
NSString *aux2 = [(NSDictionary*)item objectForKey:#"Numero"];
NSString *aux3 = [(NSDictionary*)item objectForKey:#"NombreTipoInstancia"];
if (aux) {
[NombreOrga addObject:aux];
}
if (aux2) {
[NombreInstancia addObject:aux2];
}
if (aux3) {
[Numero addObject:aux3];
}
} else {
NSLog(#"item %# is not a dictionary",item);
}
}
}
else {
NSLog(#"Its probably a DICTIONARY!.");
}
It's very strange, sometimes NSLog tells me "Its probably a DICTIONARY!" and the value is empty and the app does not work. And sometimes NSLog tells me "Its an ARRAY!" and the application works correctly.
But the data returned by the SCRIPT are always the same!
Thank you very much everyone for your help.
I am sending a request to a server in the following way:
- (void) getData
{
NSString *url= #"http://example.com";
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
exampleConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
And for this the response is a JSON file, which I am parsing as follows:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Connection did finish loading %#",[connection currentRequest]);
NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingAllowFragments error:nil];
NSLog(#"%#", exampleDictionary); // which gives me null
}
The response worked fine earlier. But now it gives me a null, which is obviously because something is hindering the conversion from JSON to NSDictionary. I investigated and found that the problem was because there were a couple of foreign characters (Chinese or something), at which the parsing process was going wrong.
I am not sure how to solve this problem. Does anyone have any ideas?
I played around with the classes and encoding options and ended up doing the following, which solved the problem.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Connection did finish loading %#",[connection currentRequest]);
NSString *res = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:[res dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingAllowFragments error:nil];
NSLog(#"%#", exampleDictionary); // gives the actual data! :)
}
am starting to build login form reading from external server via http request i need to parse json result to get user name
- (IBAction)getlogin:(UIButton *)sender {
NSString *rawStrusername = [NSString stringWithFormat:#"username=%#",_username.text];
NSString *rawStrpassword = [NSString stringWithFormat:#"password=%#",_password.text];
NSString *post = [NSString stringWithFormat:#"%#&%#", rawStrusername, rawStrpassword];
// NSString *post = #"rawStrusername&rawStrpassword";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
/* NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]]; */
NSURL *url = [NSURL URLWithString:#"http://www.othaimmarkets.com/my_services_path/user/login.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[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];
NSLog(#"responseData: %#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
//NSLog(#"responseData: %#", responseData);
}
I get this result:
{"sessid":"g2ev7til6d750ducrkege0cbj2","session_name":"SESS02795057fe9e6b2fc0777bf4057b248f","user":{"uid":"617","name":"mohammed.abdelrasoul#gmail.com","mail":"mohammed.abdelrasoul#gmail.com","mode":"0","sort":"0","threshold":"0","theme":"","signature":"","signature_format":"0","created":"1316602317","access":"1352643854","login":"1352666338","status":"1","timezone":"10800","language":"ar","picture":"","init":"mohammed.abdelrasoul#gmail.com","data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}","country_iso_code_2":"SA","timezone_name":"Asia/Riyadh","block":{"webform":{"client-block-88":1}},"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb","contact":0,"roles":{"2":"authenticated user"}}}
Or, formatted for the sake of legibility:
{
"sessid":"g2ev7til6d750ducrkege0cbj2",
"session_name":"SESS02795057fe9e6b2fc0777bf4057b248f",
"user":{
"uid":"617",
"name":"mohammed.abdelrasoul#gmail.com",
"mail":"mohammed.abdelrasoul#gmail.com",
"mode":"0",
"sort":"0",
"threshold":"0",
"theme":"",
"signature":"",
"signature_format":"0",
"created":"1316602317",
"access":"1352643854",
"login":"1352666338",
"status":"1",
"timezone":"10800",
"language":"ar",
"picture":"",
"init":"mohammed.abdelrasoul#gmail.com",
"data":"a:5:{s:18:\"country_iso_code_2\";s:2:\"SA\";s:13:\"timezone_name\";s:11:\"Asia/Riyadh\";s:5:\"block\";a:1:{s:7:\"webform\";a:1:{s:15:\"client-block-88\";i:1;}}s:13:\"form_build_id\";s:37:\"form-3ae73833f08accc7abe5517347ea87eb\";s:7:\"contact\";i:0;}",
"country_iso_code_2":"SA",
"timezone_name":"Asia/Riyadh",
"block":{
"webform":{
"client-block-88":1
}
},
"form_build_id":"form-3ae73833f08accc7abe5517347ea87eb",
"contact":0,
"roles":{
"2":"authenticated user"
}
}
}
how i can get the objects data or parse the result to get user name
any help or examples will be appreciated
You need to use the NSJSONSerialization class method, JSONObjectWithData:options:error: to create an NSDictionary:
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
if (! error) {
NSLog(#"%#",jsonDict);
}else{
NSLog(#"%#",error.localizedDescription);
}
This will get you to the point where you can look at the dictionary, which will be easier to read. It looks like you need to use objectForKey:#"sessid" to get you to user, then objectForKey#"user", then objectForKey:#"name" to get you to the name.
Check out this framework for parsing json. https://github.com/stig/json-framework/
Also check out this answer iPhone/iOS JSON parsing tutorial. You'll find a link to a tutorial you can do to get acquainted with json parsing in ios.
See this answer and some code :
NSMutableData *data; // Contains data received from the URL connection declares in header
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataIn
{
// Do it this way because connection doesn't guarantee all the data is in
POLLog(#" Tide View connection");
[data appendData:dataIn];
}
- (void) connectionDidFinishLoading:(NSURLConnection *) conn
{
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *results = [jsonString JSONValue]; // This is a new category added to the NSString by SBJSON
//100 parameters
for (int n=0;n<=100;n++)
{
// Get all the returned results
params[n] = [[results objectForKey:[NSString stringWithFormat:#"param%d",n]] floatValue];
}
To expand upon rdelmar's answer (which I think you should accept), you can use NSJSONSerialization and then navigate the NSDictionary results to extract the userName:
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&error];
if (error == nil) {
NSDictionary *userDictionary = [jsonDict objectForKey:#"user"];
NSString *userName = [userDictionary objectForKey:#"name"];
// do what you need with the userName
} else {
NSLog(#"%#",error.localizedDescription);
}
Or if using the latest version of Xcode, you can replace those objectForKey references with the even more concise Modern Objective-C syntax:
NSDictionary *userDictionary = jsonDict[#"user"];
NSString *userName = userDictionary[#"name"];