I am retriving some file from the web containing data in a specific format which I would like to parse. However I know only how to get the file from the web:
dispatch_async(server_queue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kURL];
[self performSelectorOnMainThread:#selector(parseData:)
withObject:data waitUntilDone:YES];
});
In the parse method I would like to tokenize each line of the file but I am not sure how to extract the lines from the NSData object.
-(void)parseData:(NSData *)responseData {
//tokenize each line of responseData
}
Any suggestion?
NSData is not in a format where you can go through to parse it. Just convert it to a NSString like this:
-(void)parseData:(NSData *)responseData
{
NSString *stringFromData = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *eachLineOfString = [stringFromData componentsSeparatedByString:#"\n"];
for (NSString *line in eachLineOfString) {
// DO SOMETHING WITH THIS LINE
}
}
Related
I am using Bing Search API and able to successfully parse the xml but not JSON.Below is the code to both parse xml and JSON,when I nslog the output of the JSON it shows "null" I don't know how to proceed from here.
-(void)searchBing:(NSString *)text{
//NSString *query1 = #"San Francisco Baseball";
NSString *query = [NSString stringWithFormat: #"'%#'",text];
//NSString *query = query1;
NSString *format = #"atom";
NSString *market = #"'en-us'";
//NSInteger top = 2;
NSMutableString *fullURL = [NSMutableString stringWithCapacity:256];
[fullURL appendString:URL];
[fullURL appendFormat:#"Web?$format=%#", format];
[fullURL appendFormat:#"&Query=%#",
[query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[fullURL appendFormat:#"&Market=%#",
[market stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// [fullURL appendFormat:#"&$top=%d", top];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:
[self getRequest:fullURL] delegate:self];
if (connection)
{
NSLog(#"Connection established");
}
else
{
NSLog(#"Connection failed");
}
}
Below where am parsing both xml(successful) and JSON(unsuccessful)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
// convert to JSON
NSLog(#"Finished loading: Received %d bytes of data",[self.responseData length]);
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
[parser setDelegate: self];
[parser parse];
NSLog(#"XMl == %#",parser);
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
NSLog(#"json data = %#",res);//getting null
}
Am using Base_64 encoding and to all viewers nothing wrong with query because getting correct information via xml parser.But I want response in JSON.
Structure sample
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"testign"
},
"Spell":{
"Total":1,
"Results":[
{
"Value":"testing"
}
]
},
"Web":{
"Total":5100,
"Offset":0,
"Results":[
{
"Title":"Testign part 2 - Tiernan OTooles Programming Blog",
"Description":"If this works, it means nothing really, but i have managed to build a .TEXT blog posting app. could be handy if i move my main blog to .TEXT, which i am thinking about..",
"Url":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DisplayUrl":"http:\/\/weblogs.asp.net\/tiernanotoole\/archive\/2004\/09\/24\/233830.aspx",
"DateTime":"2008-10-21T05:08:05Z"
}
]
}
}
}
From your post:
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: self.responseData];
.
.
.
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&myError];
It looks like you're trying to use the same data as XML and JSON. You can't do that. The data returned from the server is in one form OR the other. It won't be both.
I am new to iOS and working on the GOOGLE-MAP-SDK. Everything is going very well, but I am not able to use the annotations in this case due to which I am not able to locate my positions which I fetched from the placeAPI of Google.
So kindly help me out with my errors.
Code File
-(IBAction)search:(id)sender
{
NSString *url = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=30.7343000,76.7933000&radius=500&types=food&name&sensor=true&key=AIzaSyCGeIN7gCxU8baq3e5eL0DU3_JHeWyKzic"];
//Formulate the string as URL object.
NSURL *googleRequestURL=[NSURL URLWithString:url];
// Retrieve the results of the URL.
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
Here is the code from which I will receive the data and want to display it on the Google map. NSLog(#"Google Data: %#", places); is giving me the out put...
I'been trying to parse JSON data retrieved from my server, but when the server sends JSON with accents or question marks, it shows as null values.
It would be great if someone could help me solve this issue.
Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *urls=[NSString stringWithFormat:#"http://myserver.myserver/myserver"];
NSLog(#"%#",urls);
NSURL *url =[NSURL URLWithString:urls];
NSData* data = [NSData dataWithContentsOfURL:url];
//fetch the data to the JSON Foundation opject.
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//process the JSON Foundation object to the view.
[self processData:json];
}
-(void)processData:(NSDictionary *) JSONObject{
NSString *kl = [JSONObject valueForKey:#"qlk"];
NSString *an= [JSONObject valueForKey:#"alk"];
NSString *bn = [JSONObject valueForKey:#"blk"];
NSString *cn =[JSONObject valueForKey:#"clk"];
NSString *dn =[JSONObject valueForKey:#"dlk"];
NSString *correcta =[JSONObject valueForKey:#"rlk"];
qkl.text=pregunta;
akl.text =an;
bkl.text =bn;
ckl.text=cn;
dkl.text=dn;
}
And the JSON
{ "qlk": "¿De qué color es el caballo blanco de Simon Bolivar?", "alk": "Negro", "blk": "Cafe", "clk": "Blanco", "dlk": "Rojo", "rlk": "c" }
Thanks.
I am building an app that makes use of google places api,i use this url
the desired link doesnt produce any results when i use it in the browser
and i use json to parse the data coming from google places but i get this unusual warning which says NSString may not respond to JSONValue
the code is as follows
-(IBAction)nearbyLocations:(id)sender
{
NSString *url=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=37.329558,122.025002&radius=500&types=atm&sensor=false&key=AIzaSyCIZ8MxCoMsfgj0ytE7azXGfjs_E__2Nhw"];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responseData
{
//parse out the json data
//NSError* error;
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonString);
NSDictionary* json =[jsonString JSONValue];
//[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//The results from Google will be an array obtained from the NSDictionary object with the key "results".
NSArray* places = [json objectForKey:#"results"];
//Write out the data to the console.
NSLog(#"Google Data: %#", places);
}
You need a larger radius. In the URL you provided, I changed radius=500 to radius=5000 and it works. New URL. Basically there are no ATMs within 500 meters of that lat/long, but there are ATMs within 5000 meters.
That's one issue. The other issue is in Tsar's comment to your question.
{"response":[33689822,64091979,69682048,74160161]}
-
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSLog(#"okRequest|| %#",responseString);
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithString:responseString];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
//all other func..
NSLog(#"%# ", status);///This func prints only "response"
}
}
How I can get array of numbers in "response"? (33689822,64091979,69682048,74160161)
Try this:
for (NSNumber *number in [statuses objectForKey:#"response"]) {
NSLog(#"%#", number);
}
You can either parse the JSON data yourself, or better, use a library like TouchJSON to do it for you.
Try using JSONFragmentValue directly.
NSString *response=[request responseString];
id usableResp = [response JSONFragmentValue];