iOS: geojson iOS access - ios

Developing for the iPad, I have created a file that i call Coordinates.geojson. I would like to access it from within a classfile called JsonDecoder.m
Here is JsonDecoder.m
#implementation JsonDecoder
- (id)initWithJson
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Coordinates" ofType:#"geojson"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSError *error;
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
return self;
}
- (NSArray*) getCoordinatesFromShelf:(NSString *) bookShelfName
{
NSArray *coordinates = [[[_json objectForKey:#"shelf1"] objectForKey:#"coordinates"]objectAtIndex:1];
for(id i in coordinates)
NSLog(#"%#",i);
return coordinates;
}
#end
And my Coordinates.geojson:
{
"shelf1": {
"name": "six.png",
"coordinates": [
[
14,
25,
329,
138
],
[
14,
185,
329,
138
],
[
14,
344,
158,
138
],
[
185,
344,
158,
138
],
[
14,
94,
158,
138
],
[
185,
500,
158,
138
]
]
}
}
How can i retreive these values from within a class file?
Thanks!

In iOS >= 5 you can parse it without external libraries
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Coordinates" ofType:#"geojson"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
But the content of the file isn't a valid JSON string.
If possible change it to something like:
{
    "shelf1": {
        "name": "six.png",
        "coordinates": [
            [
                14,
                25,
                329,
                138
            ],
            [
                14,
                185,
                329,
                138
            ],
            [
                14,
                344,
                158,
                138
            ],
            [
                185,
                344,
                158,
                138
            ],
            [
                14,
                94,
                158,
                138
            ],
            [
                185,
                500,
                158,
                138
            ]
        ]
    }
}
Then you can access it with:
NSDictionary *shelf1 = [json objectForKey:#"shelf1"];
//OR
NSArray *coordinates = [[json objectForKey:#"shelf1"] objectForKey:#"coordinates"];

Solved it.
The above worked perfectly
I had forgot to set target membership to my project for the geojson file.
To do this, mark your jsonfile, click on the fileinspector and toogle the checkbox of your project at "Target Membership"
Thanks.

Related

covert json into dictionary in ios

i am try to convert this json data into dictionary but I can't please help me.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I know only to convert from Dictionary to JSON like this
NSMutableDictionary * location = [[NSMutableDictionary alloc]init];
[location setValue:mobileCountryCode forKey:#"mobileCountryCode"];
[location setValue:mobileNetworkCode forKey:#"mobileNetworkCode"];
[location setValue:cellId forKey:#"cellId"];
[location setValue:locationAreaCode forKey:#"locationAreaCode"];
NSData *data = [NSJSONSerialization dataWithJSONObject:requestbodyInputDict options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
so please help me how to revers this process how to handle this.
Just check this code. It will convert your json to NSdictionary
NSString *jsonString = #"{ \"homeMobileCountryCode\": 310, \"homeMobileNetworkCode\": 260, \"radioType\": \"gsm\", \"carrier\": \"T-Mobile\", \"cellTowers\": [ { \"cellId\": 39627456, \"locationAreaCode\": 40495, \"mobileCountryCode\": 310, \"mobileNetworkCode\": 260, \"age\": 0, \"signalStrength\": -95 } ], \"wifiAccessPoints\": [ { \"macAddress\": \"01:23:45:67:89:AB\", \"signalStrength\": 8, \"age\": 0, \"signalToNoiseRatio\": -65, \"channel\": 8 } ] }";
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
Use String replace method to replace " with \" it will work
what you are doing is you are directly accessing the "mobileCountryCode", "mobileNetworkCode" and so on.. which are element of json array "cellTowers" so if you want those values you can first have an array of "cellTowers" and there you go...

Get nested data from local JSON file

Now that I have the NSDictionary object JSONDictionary, how do I get the nested data inside of it?
NSString *JSONFilePath = [[NSBundle mainBundle] pathForResource:#"sAPI" ofType:#"json"];
NSData *JSONData = [NSData dataWithContentsOfFile:JSONFilePath];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
NSLog(#"Dictionary: %#", JSONDictionary);
sAPI.json snippet:
{
"ss": [{
"name": "bl",
},
"ls": [{
"name": "ML",
"abbreviation": "ml",
"id": 10,
Since you asked me to do this in a comment on a different answer, I'll answer it here. To get the name value of one of the leagues, follow this
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil]; //root object
NSArray *sports = JSONDictionary[#"sports"]; //array containing all sports (baseball, football, etc.)
NSDictionary *baseball = sports[0]; //dictionary containing info about baseball
NSArray *baseballLeagues = baseball[#"leagues"]; //array containing all leagues for baseball
NSDictionary *MLB = baseballLeagues[0]; //dictionary for only the MLB league
NSString *MLBName = MLB[#"name"]; //the full name of the MLB
This example only works for the MLB, but can easily be changed by finding the index of the other league or sport you want to use.
Note that the square brackets used in this answer are shorthand for the following methods
dictionary[#"key"]; -short for-> [dictionary objectForKey:#"key"];
array[0]; -short for-> [array objectAtIndex:0];

json iOS parsing error

I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding

iOS: Path to Twitter URL using JSON?

I'm trying to pull in the first url of a tweet using -objectForKey:, and I was wondering how I can pull in the expanded url in 1 go.
Here's the json:
"entities":{
"hashtags":[
],
"symbols":[
],
"urls":[
{
"url":"http:\/\/t.co\/example",
"expanded_url":"http:\/\/example.com\/hi",
"display_url":"example.com\/hi",
"indices":[
46,
68
]
}
],
"user_mentions":[
]
},
This is what I tried: NSLog(#"URL FOUND: %#", [JSON objectForKey:#"entities/urls/expanded_url"]);
but I got (null).
This code will be help for you
NSArray *urls = [[JSON objectForKey:#"entities"] objectForKey:#"urls"];
NSString *url = [[urls objectAtIndex:0] objectForKey:#"url"];
NSLog(#"%#",url);
"urls":[
{
"url":"http:\/\/t.co\/example",
"expanded_url":"http:\/\/example.com\/hi",
"display_url":"example.com\/hi",
"indices":[
46,
68
]
}
],
Here, value of urls is an array, so you should use path like entities/urls[0]/expanded_url
Update:
I don't know which JSON decode library you use.
Take famous JSONKit(https://github.com/johnezang/JSONKit) as an example:
NSString *str = #"{\"entities\":{\"urls\":[{\"url\":\"http://t.co/example\"}]}}";
NSDictionary *dict = [str objectFromJSONString];
NSLog(#"URL: %#",dict[#"entities"][#"urls"][0][#"url"]);

iOS JSon parsing, array in array

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?
Here is my json:
{
"Language": "EN",
"Place": [
{
"City": "Stockholm",
"Name": "Slussen",
"Commute": [
"Subway",
"Bus"
]
},
{
"City": "Gothenburg",
"Name": "Central station",
"Commute": [
"Train",
"Bus"
]
}
]
}
Here is my code:
NSString *textPath = [[NSBundle mainBundle] pathForResource:#"Places" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSArray* AllPlaces = [json objectForKey:#"Place"];
for(int n = 0; n < [AllPlaces count]; n++)
{
PlaceItem* item = [[PlaceItem alloc]init];
NSDictionary* place = [AllPlaces objectAtIndex:n];
item.City = [place objectForKey:#"City"];
item.Name = [place objectForKey:#"Name"];
NSDictionary* commutes = [json objectForKey:#"Commute"];
[self.placeArray addObject:(item)];
}
Your code should be:
NSArray* commutes = [place objectForKey:#"Commute"];
Thwt would give back an array holding "Subway" and "Bus".
I think the problem is the access to json, it should be place instead:
NSArray* commutes = [place objectForKey:#"Commute"];
NSArray *commutes = [place objectForKey:#"Commute"];
This will give you an NSArray with "Subway" and "Bus".
You can considerably shrink you code using KVC Collection Operators:
NSArray *commutes = [json valueForKeyPath:#"Place.#distinctUnionOfArrays.Commute"];
If you want all repeated commutes use #unionOfArrays modifier.

Resources