Getting null from NSDictionary when NSJSONSerialization is being used - ios

I am new to developing and stackoverflow please help me. i am trying to do a simple application where the YQL link is used to get local data and display it in table format. For that i am converting the data into dictionary , later i want to send it into table. But when i tried to convert data to Dictionary it says null. Please help me. Check the Screenshot below. Thanks in advance.
NSString *str = #"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
Here i took json query into a string (*str)
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
// NSString *stringFromData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// NSLog(#"%#", stringFromData);
When i tried to implement this commented code im getting the result as expected, but i want to put all the data into dictionary and display it, so i tried to convert the data into dictionary
NSDictionary *dataFromWeb = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSDictionary *queryDict = [dataFromWeb objectForKey:#"query"];
NSDictionary *results = [dataFromWeb objectForKey:#"results"];
NSString *allResults = [queryDict objectForKey:#"Results"];
NSLog(#"%#", dataFromWeb);
}

The response returning from Yahoo API is XML by default. You should append format=json to the querystring in order to get the response in JSON format so you can parse it using NSJSONSerialization class:
https://query.yahooapis.com/v1/public/yql?format=json&q=select...

Your Api Return xml data so you need to do xml parsing
NSJSONSerialization is used for json parsing
NSString *str = #"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
NSURL *UrlFromStr = [NSURL URLWithString:str];
hit this UrlFromStr on your browser you see it return xml data not json
use NSXMLParser to parse xml data

Please Use NSXMLParser To Parse xml data instead of NSJSONSerialization.
NSJSONSerialization is used to parse JSON data.
Declare in .h file
#property (nonatomic, strong) NSXMLParser *xmlParser;
in .m file.
NSString *str = #"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20local.search%20where%20zip%3D'94085'%20and%20query%3D'pizza'&diagnostics=true";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
self.xmlParser = [[NSXMLParser alloc] initWithData:data];
self.xmlParser.delegate = self;
// Initialize the mutable string that we'll use during parsing.
self.foundValue = [[NSMutableString alloc] init];
// Start parsing.
[self.xmlParser parse];

The format of objects you wanna parse is XML,but you use the class of ParseJSON to parse it ,so it return NULL.You can use the class of NSXML to parse it and then set its delegate to execute the related methods...Good luck to you ..

your Api is not a json its XML format use the XML Parser, visit below link,
http://www.theappguruz.com/blog/xmlparsing-with-nsxmlparser-tutorial
hope its helpful.

Related

How to parse JSON data from textual file in Objective-C

I know, JSON parsing questions are asked over and over again, but still I can't find any answer to this one.
I've been trying to read and parse a textual JSON file using NSJSONSerialization to no avail.
I've tried using the same JSON data from a NSString and it did work.
Here's the code:
NSError *error;
NSString *jsonString1 = [NSString stringWithContentsOfFile:jsonFilePath
encoding:NSUTF8StringEncoding
error:&error];
NSData *jsonData1 = [jsonString1 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:jsonData1
options:0
error:&error];
NSString *jsonString2 = #"{\"key\":\"value\"}";
NSData *jsonData2 = [jsonString2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonObject2 = [NSJSONSerialization JSONObjectWithData:jsonData2
options:0
error:&error];
- The text file contains one line: {"key":"value"}
- jsonString1 = #"{"key":"value"}"
- jsonString2 = #"{\"key\":\"value\"}"
- jsonData1 is 23 bytes in size
- jsonData2 is 15 bytes in size
- jsonObject1 is nil and I get error code 3840
- jsonObject2 is a valid dictionary
Seems like the problem is with reading the file, since the NSStrings and NSDatas differ, but what am I doing wrong here and how can I fix it?
Most likely you file contains some unprintable characters (e.g. \0) that trigger the failure. Printing the error message will tell you at what position the first invalid characters occurs.
For example, try printing "{\"key\":\u{0000}\"value\"}" and you'll seem to get a valid JSON, however decoding it fails.
I always do a check on the return value when doing anything with NSUTF8StringEncoding and if nil, then try NSASCIIStringEncoding:
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
if (jsonString == nil) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
}
return jsonString;

How do I urlencode this NSString that contains a JSON inside it?

I have the following json string that should be sent to the backend
{
id = "MU_200255802";
keywords = (
Talk,
games,
meetup,
time,
meet,
"Time for Another Game"
);
}
So before this JSON I have the java servlet URL something like
http://....net/servletName?
How should I urlencode the json string and the url because even after trying several options, I keep getting bad url as an error back in the delegate method. What is the right way to do it/
I tried encoding using
NSString *urlStringEncoded = [[NSString stringWithString:urlString] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
and also used other encoding formats too.
Use this to create json string
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:#"Your object" options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
You can use Google Toolbox for Mac, check it out here, https://code.google.com/p/google-toolbox-for-mac/source/checkout
There are Classes named GTMNSString+HTML,GTMNSString+XML,GTMNSString+URLArguments, which contains many encoding methods for you.

how to send an array as a parameter to json service in iOS

I am using iPhone JSON Web Service based app.I need to pass input parameter as an array to a JSON web Service, how can I do this?
Array Contains 12 elements.
Here am providing sample service...
input parametes for this service:
dev_id = 1;
dev_name= josh and array items (projectslist,companyidentifier)
http://www.jyoshna.com/api/developer.php?dev_id=1&dev_name=josh&(Here i need to pass the array elements)
can any help us how to pass array as a input parameter to the json service?
First you have to convert array as JSON string
NSString *requestString=[jsonParser stringWithObject:array];
convert string to data
NSData *data=[requestString dataUsingEncoding:NSUTF8StringEncoding];
set that data as request Body
[request setHTTPBody:data];
You have to serialize the array and pass as an argument. Dont forget to unserialize in server side
you will need to create an NSMutabelDictionary of your array then JSON encode it, you can then send the resulting string you your webservice however you choose. I tend to build a POST request and send it that way
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *tagData = [[NSMutableDictionary alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *keyString = [NSString stringWithFormat:#"key%i", i];
[tagData setObject:[array objectAtIndex:i] forKey:keyString];
}
[jsonDict setObject:tagData forKey:#"entries"];
NSData* data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted error:&error];
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It is the sgtring aStr that you need to send

Parsing JSON object for iOS application

Currently, I have within my iPhone app a URL with which contains a JSON object that I must parse.
I am able to fetch the JSON object, convert the object to an NSString, now the issue is parsing the object/NSString object.
I am currently using SBJSON.
How do I go about iterating through the key elements of the JSON object using SBJSON's framework?
{
"status":"SUCCESS",
"fields":[
{
"type":"instant",
"field":"GenerationPower",
"label":"now",
The JSON object is MUCH larger than just these keys and key elements but once this issue is resolved, I'm sure the rest of the JSON object will be easy since i'll have a reference.
Thank you Stackoverflow!
EDIT:
Here's some code to clarify my issue.
+ (NSString *) pullingInfo
{
NSURL *solarWebURL = [NSURL URLWithString:myurl];
if (solarWebURL)
{
NSLog(#"Calling: %#", solarWebURL);
NSData *jsonData = [NSData dataWithContentsOfURL:solarWebURL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return jsonString;
}
NSString* errorMessage = #"Error reading URL";
return errorMessage;
}
+ (NSDictionary *) jsonDictionaryObject
{
NSDictionary * jsonDictionary = [[NSDictionary alloc] init];
NSString * monroeString = [MonroeParser pullingInfo];
return jsonDictionary;
}
So as I said before, I have already loaded the JSON object into an NSString object "jsonString". Now I would like to start parsing the string.
I figure I may not even need to use JSON's framework for parsing, I can probably just parse the NSString using NSString conventions provided by Apple.
Any idea's? But maybe this isn't efficient....
Sine you are using SBJSON, why are you even converting the NSData to an NSString? You can use -objectWithData method for SBJSONParser to directly read the NSData into an NSDictionary.
http://sbjson.org/api/3.2/Classes/SBJsonParser.html#//api/name/objectWithData:
Let pullingInfo return an id. And in you calling function check if the id is of type NSDictionary or NSArray and parse accordingly.

NSJSONSerialization from NSString

Is it possible if I have a NSString and I want to use NSJSONSerialization? How do I do this?
First you will need to convert your NSString to NSData by doing the following
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
then simply use the JSONObjectWithData method to convert it to JSON
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
You need to convert your NSString to NSData, at that point you can use the +[NSJSONSerialization JSONObjectWithData:options:error:] method.
NSString * jsonString = YOUR_STRING;
NSData * data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!json) {
// handle error
}
You can convert your string to NSData by saying:
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
You can then use it with NSJSONSerialization. Note however that NSJSONSerialization is iOS5 only, so you might be better off using a library like TouchJSON or JSONKit, both of which let you work directly with strings anyway, saving you the step of converting to NSData.
I wrote a blog post that demonstrates how to wrap the native iOS JSON class in a general protocol together with an implementation that use the native iOS JSON class.
This approach makes it a lot easier to use the native functionality and reduces the amount of code you have to write. Furthermore, it makes it a lot easier to switch out the native implementation with, say, JSONKit, if the native one would prove to be insufficient.
http://danielsaidi.com/blog/2012/07/04/json-in-ios
The blog post contains all the code you need. Just copy / paste :)
Hope it helps!

Resources