How to parse this - objective-c

I'm experimenting with googles url shortener goo.gl and at the moment it send the url to goo.gl and returns this:
{
"kind": "urlshortener#url",
"id": "http://goo.gl/kyPI",
"longUrl": "http://dsfsd.com/"
}
I think it's JSON but I'm having trouble with that because of ARC. Is there anyway else I could parse the string with key "id"?

If your app targets iOS 5 you can use NSJSONSeralization class of Apple.
(Let's assume youryour received is called theData)
NSError *error=nil;
id result=[NSJSONSerialization JSONObjectWithData:theData options:
NSJSONReadingMutableContainers error:&error];
//to retrieve the 'kind' value of the object
NSLog("Kind: %#",[result objectForKey:#"kind"]);

It's JSON, you can use a framework like SBJson to parse it. See http://stig.github.com/json-framework/

Related

How to send any params in JSONHTTP with Objective c?

I need send a post json request to an url. This service need two identifiers, ow can I sent it with JSONHTTPClient??
With postman I write:
{
"token" : "apitoken",
"identifier" : 1
}
But with objective c code I dont know how to add this two elements into request:
//add extra headers
[[JSONHTTPClient requestHeaders] setValue:#"MySecret" forKey:#"AuthorizationToken"];
//make post, get requests
[JSONHTTPClient postJSONFromURLWithString:#"http://myd.com/api"
params:#{}
completion:^(id json, JSONModelError *err) {
//check err, process json ...
}];
Populate the params dictionary.
//make post, get requests
[JSONHTTPClient postJSONFromURLWithString:#"http://myd.com/api"
params:#{ #"token": #"apitoken",
#"identifier": #1 }
completion:^(id json, JSONModelError *err) {
//check err, process json ...
}];
See the JSONHTTPClient Class Reference:
postJSONFromURLWithString:params:completion:
params:
a dictionary of key / value pairs to be send as variables to the request

Parsing a config file

I have a config file whose content is something like this:
main = {
delay = 10000;
inputs = (
{
enabled = true;
ip = "127.0.0.1";
port = 10001;
file = "c:\abc.txt";
},
{
enabled = true;
ip = "127.0.0.1";
port = 10002;
file = "c:\myfile.txt";
},
);
}
Now, I want to parse this file, and for example, get the port number of the second input (i.e., 10002 in this example), etc.
Do you know what is the easiest way to do so in objective C?
Thanks!
Make sure it's a valid JSON file and then create a NSJSONSerialization object from the NSData of the file after opening it.
NSJSONSerialization *config = [[NSJSONSerialization JSONObjectWithData:DATAFROMFILE options:NSJSONReadingMutableContainers error:nil];
Then to access the second input port:
config[#"inputs"][1][#"port"]
But the best way to do this would be to create a model from each input so you could access the properties as strongly typed properties instead of by key.
ie. config.port instead of configInput[#"port"]
Looks like your config contents were output by NSLog, which results in invalid JSON hence assuming that your actual config file is a valid JSON object, following code should get you what you need:
//Don't forget to replace "configfile" with your config file name in the project
NSString *configPath = [[NSBundle mainBundle] pathForResource:#"configfile" ofType:nil];
NSData *data = [[NSFileManager defaultManager] contentsAtPath:configPath];
NSDictionary *config = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *ports = [config valueForKeyPath:#"main.inputs.port"];
//ports[0] is 10001
//ports[1] is 10002
Here you can verify if your JSON is valid: http://jsonlint.com. This is how your valid JSON confi should look like:
{
"main": {
"delay": "10000",
"inputs": [
{
"enabled": true,
"ip": "127.0.0.1",
"port": 10001,
"file": "c: \\abc.txt"
},
{
"enabled": true,
"ip": "127.0.0.1",
"port": 10002,
"file": "c: \\myfile.txt"
}
]
}
}
EDIT:
I would personally use a model framework rather than just a json parser to save you from a ton of manual work that comes with built-in NSJSONSerialization class. Here are couple of pretty good ones:
1) GitHub Mantle - https://github.com/MantleFramework/Mantle
I use it where ever I can. It is very well written and thought out framework but has a little bit of learning curve involved, which probably is true to any new piece of software.
2) SBJson - https://github.com/stig/json-framework
You can use SBJson if you just wanna get the job done, it has been pretty popular, especially before Mantle and other frameworks became available.
I hope it helps.
If you are able to change or modify the configuration file format to json or plist, you could simply use built in readers an parsers.
Else, there are third party approaches like libconfig.
Also this question may help.

JSON error parsing a dictionary from a ruby on rails server in objective c app

I have a small Ruby on Rails server that replies to get requests by a objective-c client. Since I need to accumulate data from different tables I decided to put it in a dictionary (hash in rails) and then send it as a JSON and on the client I use the iOS 5 JSON framework to reconstruct the dictionary. Here are simpler parts of my code:
format.json { render :json => {:message_type => 'getBaseOpReply',
:base_longitude => #operator.base_longitude,
:base_latitude => #operator.base_latitude} }
and on the client I use the connection data delegate where in connection:didReceiveData I accumulate the data in responseData and in connectionDidFinishLoading I do:
NSError *error;
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
I get the following error:
ErrorDomain=NSCocoaErrorDomain Code=3840 ... JSON text did not start with array or object etc.
I tried with all the different options for the JSONObjectWithData:options:error: and I get the same error except when I use the NSJSONReadingAllowFragments. Then it is a bit different saying Invalid value around character 0.
I assume my server is not properly constructing the dictionary but please help me out. Thanks in advance!

iOS – Facebook SDK, parsing results

In my -request:didLoad: delegate method I'm NSLoging the results but I can't figure out what's the content?
It looks like result is an NSArray but what is inside it? how do I parse the data?
A sample of the log looks like this:
result: (
{
"fql_result_set" = (
{
uid2 = 1234567;
},
{
uid2 = 12345678;
}
);
name = queryID;
},
{
"fql_result_set" = (
{
"birthday_date" = "05/12/1987";
name = "John Doe";
},
{
"birthday_date" = "03/01/1978";
name = "Jane Doe";
}
);
name = queryBirthday;
}
)
The Facebook iOS tutorial, in "Step 6: Using the Graph API", says
Note that the server response will be in JSON string format. The SDK uses an open source JSON library https://github.com/stig/json-framework/ to parse the result. If a parsing error occurs, the SDK will callback request:didFailWithError: in your delegate.
A successful request will callback request:didLoad: in your delegate. The result passed to your delegate can be an NSArray, if there are multiple results, or an NSDictionary if there is only a single result.
In your example, everything printed by NSLog inside "()" is part of an NSArray, while everything inside "{}" (which also have keys incidentally) is part of an NSDictionary and therefore accessible by key (name).
http://developers.facebook.com/docs/mobile/ios/build/
According to https://developers.facebook.com/docs/reference/api/, all 'responses' are JSON-Objects. To parse these, iOS 5 provides a class called NSJSONSerialization (NSJSONSerialization Class Reference)
You normally parse it as follows:
NSDictionary *dictionaryJSON = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];

Find the number of routes between two places

I need to find out the number of routes from a source to a destination using the Google maps API, and then find, among those, which one is the shortest route.
I am able to get one route by using this code
-(NSArray*) calculateRoutesFrom:(CLLocationCoordinate2D) f to: (CLLocationCoordinate2D) t {
NSString* saddr = [NSString stringWithFormat:#"%f,%f", f.latitude, f.longitude];
NSString* daddr = [NSString stringWithFormat:#"%f,%f", t.latitude, t.longitude];
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps?output=dragdir&saddr=%#&daddr=%#", saddr, daddr];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSLog(#"api url: %#", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl];
NSString* encodedPoints = [apiResponse stringByMatching:#"points:\\\"([^\\\"]*)\\\"" capture:1L];
return [self decodePolyLine:[encodedPoints mutableCopy]];
}
but I'm unable to get multiple routes.
I'm new to using the Google Maps API; I followed this tutorial.
How can I do this? Can any one please post some sample code or a tutorial?
alternatives (optional), if set to
true, specifies that the Directions
service may provide more than one
route alternative in the response.
Note that providing route alternatives
may increase the response time from
the server.
From The Google Directions API
You need to add in your query link alternatives=true
For getting the multiple routes you have to use the standard google direction api. Through this api you can get different routes on the bases of traveling mode you select in api ie driving, walking or bicycling( bicycling route availabel in US only) For example : http://maps.googleapis.com/maps/api/directions/xml?origin=srcLatitude,srcLongitude&destination=destLatitude,destLongitude&mode=driving&sensor=false
Here you can give the source and destination latitude and longitude and change the value of mode parameter to driving, walking or bicycling to get multiple route.