How do I extract a value from the following code? - iphone

How do I extract just the "token" value from the following code? I'm looking to save this value into a string.
Is meta an array? If so how would I extract the data from the "token" value?
thanks for any help
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
Response ==> {"meta":[],"data":{"token":"IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU="}}
2013-07-19 15:10:23.139 appName [11190:907] {
data = {
token = "IVZ2ciRkbVtDLUl3YmhwOTkyXzpRR1M3LUUsRiElfWF6T3I6dCxsRWg6di1XcyR6OTUzZHhVazdLTEJ7blU5O258d2xRTXg0VUxwQXBlNHRSOXd2VXZ1aG1RfFhQQjJsSkkoc2IuOTFyYkYodyhAe2RldXR1aDF3RClXWyhoMiU=";
};
meta = (
);
}

I believe the data is in JSON format. In that case, this should work.
NSError *error = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];

I'd just do this:
NSData *responseData = [NSData dataWithContentsOfURL:yourURL];
NSString *token = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:NULL][#"data"][#"token"];
It will be nil if there's any error.

In your Case, meta is an Array and data is a Dictionary. If your Response is properly formatted in JSON then you can use the below sample code to get the TokenString and metaArray.
Sample Code :
NSData *data = [NSData dataWithContentsOfURL:yourURL];
NSError* error = nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *token = [[responseDict objectForKey:#"data"] objectForKey:#"token"];
NSArray *meta = [responseDict objectForKey:#"meta"];
NSLog(#"\ntoken :: %#\nmeta :: %#",token,meta);
PS : To know more about JSON response , take a look at this Answer.

Related

How to format a ReturnString Array from a webService

I get a returnString from a WebService in iOS:
[
{"datum":"2013-07-24
09:38:43","nummer":"1017348010239480212208","anmerkung":"Elektronische
Auftragsdaten wurden vom Versender
\u00fcbermittelt"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Verteilung"},{"datum":"2013-07-24
09:38:44","nummer":"1017348010239480212208","anmerkung":"Sendung in
Zustellung"},{"datum":"2013-07-24
09:26:06","nummer":"1017348010239480212208","anmerkung":"Empf\u00e4nger
nicht angetroffen - benachrichtigt"},{"datum":"2013-07-19
06:24:42","nummer":"1017348010239480212208","anmerkung":"Sendung in
Post-Empfangsbox eingelangt"}
]
the Objective C Code works fine:
#import "SBJson.h"
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
self.textfeld.text = [NSString stringWithFormat: #"%#", returnString];
I try to format the Response with NSMutableArray or NSArray and JSONValue but without success :
NSMutableArray *meinErgebnis = [responseString JSONValue];
NSLog(#"%#",[[meinErgebnis objectAtIndex:0] objectAtIndex:1]);
How to format the returnCode like that?
Nummer: 1017348010239480212208
Anmerkung: Sendung in Verteilung
Nummer: 1017348010239480212208
Anmerkung: Sendung in Post-Empfangsbox
You can obtain Data with following method,
id Data = [NSJSONSerialization JSONObjectWithData:fetchedData options:kNilOptions error:&error];
Then you can loop the data accordingly. For your example,
for(id object in Data)
{
NSLog(#"%#",[object valueForKey:#"nummer"]);
NSLog(#"%#",[object valueForKey:#"anmerkung"]);
}
The loop used above is of fast Enumeration type. Hope this helps.
Use following code for get all the values of nummer and anmerkung from your mutable array.
NSMutableArray *meinErgebnis = [responseString JSONValue];
for(int i = 0; i < meinErgebnis.count; i++)
{
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"nummer"]);
NSLog(#"%#",[[meinErgebnis objectAtIndex:i] objectForKey:#"anmerkung"]);
}

Json web service https

Could you help me, with a example, where i consume a json webservice in a https url.
i have tried:
where urlConParametros is a https url.
NSString* encriptado = nil;
NSString* urlConParametros = [NSString stringWithFormat:#"%#%#?%#=%#", URL, metodo, key, valorSinEcncriptar];
NSError* error;
if(encriptado == nil){
NSMutableURLRequest *getRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlConParametros]];
[getRequest setHTTPMethod:#"GET"];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 =[NSURLConnection sendSynchronousRequest:getRequest returningResponse:&urlResponse error:&requestError];
NSString* data = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlConParametros] encoding:NSUTF8StringEncoding
error:&error];
return data;
}
but return data nil.
My problem is that with http, the same web service response the correct data, but when it doing with https, the response is nil.
Please add some more details in the Question about What you want exactly, What you have tried and What are the Problems you are facing while implementation ?
If you want to GET some data from the Web Service , you can get it like this. :
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlConParametros]];
NSString *respStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"My Response :: %#",respStr);
If the Response is in JSON Format then you should do something like this :
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlConParametros]];
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"My Response :: %#",json);
Take a look at the Sample Code for AdvancedURLConnections.

how can I get formatted address

How can I get formatted address like Covington, AL, USA of google web service in my iphone
from the below url
http://maps.google.com/maps/api/geocode/xml?latlng=31.319016,-86.399871&sensor=false
- (void) getAddress
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://maps.google.com/maps/api/geocode/json?latlng=31.319016,-86.399871&sensor=false"]];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSString *str = [[[dict objectForKey:#"results"] objectAtIndex:0] valueForKey:#"formatted_address"];
NSLog(#"Address = %#", str);
}
Use this json this is much faster that xml.

NSJSONSerialization Not Creating Key Value Pairs

I am using iOS 5 new feature to parse JSON and I have no idea that why I am not getting any key value pairs. "aStr" (string representation of data) is putting the right JSON on the output window but I am getting nothing in "dicData" and there is no error either.
Any help is greatly appreciated.
This is what I am using
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.macscandal.com/?json=get_post&post_id=436"]];
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
//NSLog(#"data = %#",aStr);
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
//NSLog(#"error = %#",error);
NSString *title = [dicData objectForKey:#"title"];
Your JSON is formatted this way:
{
"status": "ok",
"post": {
"id": 436,
"type": "post",
"slug": "foxconn-likely-to-get-assembly-contract-for-apple-tv-set",
"url": "http:\/\/www.macscandal.com\/index.php\/2011\/12\/28\/foxconn-likely-to-get-assembly-contract-for-apple-tv-set\/",
"status": "publish",
"title": "Foxconn Likely to get Assembly Contract for Apple TV Set",
...
I haven't used NSJSONSerialization but just following the natural JSON parsing alg this is how I would try to get it.
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSDictionary *postData = [dicData objectForKey:#"post"];
NSString *title = [postData objectForKey:#"title"];
EDIT
Just a simple check method:
-(void)check{
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.macscandal.com/?json=get_post&post_id=436"]];
NSDictionary *dicData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
NSDictionary *postData = [dicData objectForKey:#"post"];
NSString *title = [postData objectForKey:#"title"];
NSLog(#"%#", title);
}

unable to parse json response from google

I am trying to parse Json response from This URL. I have used SBJsonParser, MTJSON and another parser but i am getting NULL in all three case.
apiUrlStr = #"http://maps.google.com/maps?output=dragdir&saddr=Delhi&daddr=Mumbai+to:hyderabad";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
SBJsonParser *json = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dictionary = [json objectWithString:apiResponse];
NSLog(#"dictionary=%#", [json objectWithString:apiResponse]);
2011-12-09 16:59:01.226 MapWithRoutes[2523:207] dictionary=(null)
Plz suggest me something
Oke if checked the url you gave with JSONlint.com and the JSON is not valid. thus can not be parsed by any library.
If you used JSONkit you can supply a NSError object with the parse call to see what went wrong:
NSError *error = nil;
NSDictionary *dictionary = [apiResponse objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if (!dictionary) {
NSLog(#"Error: %#", error);
}