iOS : JSON String to NSArray not working as expected - ios

How to parse a a JSON string in iOS app? Using SBJSON. Running the code below. Getting data is successful but the count on the number of entries in the array is zero even tho the JSON string contains entries. My question is how query the JSON string in a loop?
Thanks!
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://safe2pee.org/api/proxlist.php?location=37.7626214,-122.4351661&distance=1"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"string equal = %#", json_string);
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON b objects
NSArray *bathrooms = [parser objectWithString:json_string error:nil];
NSLog(#"count = %d", [bathrooms count]);
// Each element in bathrooms is a single bathroom
// represented as a NSDictionary
for (NSDictionary *bathroom in bathrooms)
{
// You can retrieve individual values using objectForKey on the bathroom NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [bathroom objectForKey:#"name"], [[bathroom objectForKey:#"lat"] objectForKey:#"long"]);
}

It's because it's not working. That's not a valid JSON string. That's 2 JSON dictionaries, back to back, with a comma in between. It's missing the wrapping []. If you actually test the result value of -objectWithString:error:, you'd see it's nil, and if you pass in an NSError** to the error parameter there, you'd get back an error message telling you it's invalid JSON.

I looked at the JSON string returned when I request the URL in your post, and it looks like it is being improperly truncated by the server. The JSON string returned contains a dictionary structure containing, among other things, a key called "bathrooms" whose value is an array of dictionary structures. Each of those bathroom dictionary structures contains several fields including "bid", "name", "lat", ..., "directions", and "comment".
When I scroll to the end of the JSON I received, I see a complete dictionary structure under the "bathrooms" array ("bid" is "MTIyIFMyUA==", "name" is "Momi Tobi's". That dictionary structure contains its closing brace but the closing "]" for the array is missing and the closing "}" for the top-level dictionary structure is missing.
You should look to the service to see why it is returning invalid JSON strings. Once you have a valid string it looks like you should be starting with an NSDictionary and parsing it something like this:
NSDictionary *result = [parser objectWithString:json_string error:nil];
NSArray *bathrooms = [result objectForKey:#"bathrooms"];

Related

Convert NSString representing an array of arrays of numbers to NSArray

I am receiving a string in my request; the string is a list of pairs of numbers, grouped with square brackets. (The list represents polygons to display inside my app.)
I need to convert it to an NSArray and parse all the numbers into coordinates.
The received string is
[[[53.502483, -113.420593], [53.503429, -113.421527], [53.503491, -113.421673], [53.503002, -113.42164], [53.502719, -113.421426], [53.502483, -113.420593]]]
All the examples I've found are just to convert a single list in text to NSArray. I couldn't find anything where there are multiple arrays in the string.
The string looks like valid JSON, so...
NSError *error;
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:nil error:&error];
Will give the array, provided string contains the input. If it's coming from a web request, you can save a step and convert the request's NSData directly.

Creating a json object from nsmutable array

I have got three nsmutablearray imageNameArray,imageSizeArray,baseArray.
I have to create a json of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
since the number of elements within document array might vary, Im trying to create nsdictionary from arrays as follows,
for (int i = 0; i< [_imageNameArray count]; i++){
[dictionary setValue:self.imageNameArray[i] forKey:#"file_name"];
[dictionary setValue:self.imageSizeArray[i] forKey:#"file_size"];
[dictionary setValue:self.baseArray[i] forKey:#"file_content"];
}
but it is not creating the json of required type. When Im trying to print it, there exists an equals to symbol between key and value.
No need to check in console that it is equal symbol or colon. If you want to send data to server then first convert it in data like,
NSDictionary *dict ; // your dict or array
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
It will convert it in colon (:) instead of =.
And if you are using AFNetworking then you not need to do this jsonserialization, you can directly pass dictionary or array as parameter in method and afnetworking manage all things.
Hope this will help :)

Getting one value from JSON API in Objective-C

I'm trying to get one value from JSON. JSON is located in NSString and it looks like this:
{"coord":{"lon":-122.38,"lat":37.57},"weather":[{"id":300,"main":"Drizzle","description":"Lekka mżawka","icon":"09d"}],"base":"stations","main":{"temp":304.74,"pressure":1017,"humidity":35,"temp_min":300.15,"temp_max":307.59},"visibility":16093,"wind":{"speed":6.7,"deg":250},"clouds":{"all":75},"dt":1437346641,"sys":{"type":1,"id":478,"message":0.0615,"country":"US","sunrise":1437311022,"sunset":1437362859},"id":5357155,"name":"Hillsborough","cod":200}
I'm interested in getting "temp". How should I do that?
Assuming your JSON string was stored as a NSString named JSONString:
NSError *error;
NSDictionary *keys = [NSJSONSerialization JSONObjectWithData:[JSONString dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers
error:&error];
NSLog(#"temp = %#", keys[#"main"][#"temp"]); // temp = 304.74
To get the main sub item in weather, which is an array with multiple items, you should point out its index to tell the selector which object in the array is the one you are looking for. In this case, it's 0:
NSLog(#"weather = %#", keys[#"weather"][0][#"main"]); // weather = Drizzle

NSMutableData to NSDictionary returning null

I'm writing a program that uses the Instagram API and I'm running into some issues with NSMutableData and NSDictionary.
Since I have to make multiple calls to the API, I decided to create a NSMutableData object, append smaller NSData objects to it and then turn the whole thing into an NSDictionary.
However, after I make a second call to NSMutableData appendData NSData, when I turn NSMutableData into an NSDictionary, the dictionary returns null.
Here's some of my code.
NSMutableData *userData = [[NSMutableData alloc]init]
NSData *feed = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%#",accessToken]]];
[userData appendData:feed];
NSData *moarData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://api.instagram.com/v1/users/17636367/media/recent?access_token=%#&max_id=%#",accessToken, maxID]]];
[userData appendData:moarData];
NSDictionary *dictTwo = [NSJSONSerialization JSONObjectWithData:userData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",dictTwo);
dictTwo returns null. However, when I make only one call to appendData, the dictionary isn't empty.
Thanks.
When you append two separate JSON responses they will not form a JSON.
You can test the final result to see if it is JSON or not with the following link:
JSON validator
You need to parse each query response separately and then apply manipulation on that data: (Ex NSMutableDictionary, NSMutableArray etc).
The first call will return an array or dictionary. Assuming it is a dictionary you would get something like:
{"some":"data"}
This can be parsed correctly. When you make two calls you get:
{"some":"data"}{"other":"data"}
This is not valid JSON. You need to parse each item separately.

iOS JSON Parse into NSDictionary and then NSArray with SBJson

It should be so simple but I cannot get it work.
Json response is
([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])
NSString *response = [request responseString];
//response is ([{"id":"1", "x":"1", "y":"2"},{"id":2, "x":"2", "y":"4"}])
SBJSON *parser = [[[SBJSON alloc] init] autorelease];
NSDictionary *jsonObject = [parser objectWithString:response error:NULL];
// jsonObject doesn't have any value here..Am I doing something wrong?
NSMutableArray Conversion = [jsonObject valueForKey:NULL];
//Even if I get the value of jsonObject. I don't know what to put for valueForKey here
Conversion shoud have two NSObjects..and each of them should have like
id:1
x:1
y:2
and
id:2
x:2
y:4
Your JSON parser will produce an NSArray from your response string, not an NSDictionary. Note that JSON parsers, including SBJSON, will return either an array object or a dictionary object, depending on the contents of the json that is being parsed.
NSArray *jsonObject = [parser objectWithString:response error:nil];
You can then access the individual items in your array (the array elements will be of type NSDictionary) and use valueForKey: to get the properties of each item.
NSDictionary *firstItem = [jsonObject objectAtIndex:0];
NSString *theID = [firstItem objectForKey:#"id"];

Resources