Issue with parsing JSON data - objective-c

I am trying to convert a string into a json object and am unsure why this is not working. When I nslog the output I am told that urldata is not valid for json serialization however when looking at the string it looks to me like valid json. I have also tried encoding it to an utf8 however it still won't serialize. Am I missing something here? - Note unnecessary code omitted from post.
Get request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSDictionary *tempDict = [NSDictionary alloc];
Parsing
if ([NSJSONSerialization isValidJSONObject:urlData] ) {
NSLog(#"is valid");
tempDict = [NSJSONSerialization JSONObjectWithData:urlData kniloptions error:&error];
}
NSLog(#"is not valid");
Definition:
isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.

As you are already mentioning in your question, isValidJSONObject
returns a Boolean value that indicates whether a given object can be
converted to JSON data
In your case, you don't want to create JSON data, but instead create a dictionary out of JSON data. :
tempDict = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
if (!tempDict) {
NSLog(#"Error parsing JSON: %#", error);
}

Related

Sending Xcode data to JSON

I am fairly new to xcode but I currently have an app that will send data to a sql database but I know it has to go through JSON first.
Say my app is simply a text box where a user enters a name and submits. How would I turn that data into JSON? What would the syntax look like?
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/
If you are sending the data through a network, then look into AFNetworking.
(added in response to a comment)
NSString *jsonFromObject(id object)
{
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject: object options: 0 error: &error];
if (error) {
NSLog(#"error creating json string: %#", error);
}
return [[NSString alloc] initWithData: jsonData encoding: NSASCIIStringEncoding];
}

isValidJSONObject not working as expected

After testing, I can only get [NSJSONSerialization isValidJSONObject:] to return a positive on JSON data that I have already parsed with [NSJSONSerialization JSONObjectWithData:options:error:].
According to the official documentation:
isValidJSONObject returns a Boolean value that indicates whether a given object can be
converted to JSON data.
However, despite the fact that the objects I am attempting to convert from JSON to a NSDictionary convert fine, isValidJSONObject returns NO.
Here is my code:
NSURL * url=[NSURL URLWithString:urlString];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error=[[NSError alloc] init];
NSMutableDictionary * dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if([NSJSONSerialization isValidJSONObject:data]){
NSLog(#"data is JSON");
}else{
NSLog(#"data is not JSON");
}
if([NSJSONSerialization isValidJSONObject:dict]){
NSLog(#"dict is JSON");
}else{
NSLog(#"dict is not JSON");
}
NSLog(#"%#",dict);
My log contains the following:
data is not JSON
dict is JSON
and then the output of dict, which at this point is a huge NSMutableDictionary object. No errors are generated when running this code, but isValidJSONObject seems to be returning the wrong value when run on data.
How can I get isValidJSONObject to work as expected?
isValidJSONObject tests if a JSON object (a NSDictionary or NSArray) can be successfully
converted to JSON data.
It is not for testing if an NSData object contains valid JSON data. To test for valid
JSON data you just call
[NSJSONSerialization JSONObjectWithData:data ...]
and check if the return value is nil or not.

Not able to read JSON from service

I am implementing forget password service in which I would pass an email address and it would return JSON to acknowledge about the sent email. The issue is that I am unable to read the response string in json, and my exception message is shown that data parameter is nil, but if I view the url in my web browser the service looks fine as mentioned below.
my code is:
NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
NSData* data = [NSData dataWithContentsOfURL: url];
#try {
NSError* error;
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];
NSLog(#"%#", [jsonDict objectForKey:#"response"]);
}
#catch (NSException *exception) {
NSLog(#"forgot password exception: %#: %#", [exception name], [exception reason]);
}
and the service response I get in my web browser is like this:
{"status":400,"response":"Your request to change password is already sent. Please check your email."}
Exception:
forgot password exception: NSInvalidArgumentException: data parameter is nil
in Objective-C exceptions are only used for fatal errors, not recoverable errors. Instead just check for nil data:
If you need to know what was the reason for failure, use:
NSError* error;
NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
NSData* data = [NSData dataWithContentsOfURL: url options:NULL error:&error];
if (data) {
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];
NSLog(#"%#", [jsonDict objectForKey:#"response"]);
}
else {
NSLog(#"forgot password error, %#", [error localizedFailureReason]);
}
There is a naming convention error: getURLForgotPassword:
A method name that begins with "get" implies that there will be a return by reference parameter. Better to just name the method: forgotPasswordURL:
These two things, exceptions and accessors prefixed with get are a basic difference from Jave.
There error says data parameter is nil. So the variable you pass for the JSON-date probably is nil.
[NSData dataWithContentsOfURL:url] probably returns nil since an error occured. Try logging that.
Also, even if it is only a small file you request, I would go for an asynchronous request in order not to block the UI.
i was facing the same problem, problem was that i have given extra space in the url string that was url string #" http:...." corrected it by removing space in the start of url string #"https:...."
Solved that by fixing service URL, my url was not encoded and had spaces inline

Parsing JSON value in objective c error?

I use ASIHTTPRequest to get a token, and I receive this string:
{Token:[{"new":"jkajshdkjashdjhasjkdhjkhd+sd==sfbjhdskfbks+sdjfbs=="}]}
I used JSON Framework from here: http://stig.github.com/json-framework.
This is the code after I get the string:
- (void)requestFinished:(ASIHTTPRequest *)req
{
NSString *responseString = [req responseString];
NSLog(#"Response: %#", [req responseString]);
// Parse the response
SBJsonParser *jsParser = [SBJsonParser new];
id content = [responseString JSONValue];
if(!content){
// Parsing error
NSLog(#"%#", jsParser.errorTrace);
}
}
NSLog(#"ID: %#", content);
I receive this error:
-JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object key string expected\" UserInfo=0x5a418a0 {NSLocalizedDescription=Object key string expected}"
)
My guess is that, the JSON Framework that I am using cant understand the response string format:
{Token:[{"new":"jkajshdkjashdjhasjkdhjkhd+sd==sfbjhdskfbks+sdjfbs=="}]}
Is there any other way to parse the value?
Happy programming,
Johnie
It was looking for a start and end " surrounding Token.
{"Token":[{"new":"jkajshdkjashdjhasjkdhjkhd+sd==sfbjhdskfbks+sdjfbs=="}]}
There's a bug in this code:
SBJsonParser *jsParser = [SBJsonParser new];
id content = [responseString JSONValue];
if(!content){
// Parsing error
NSLog(#"%#", jsParser.errorTrace);
}
You instantiate a parser, jsParser, but don't use it to parse the string. (The JSONValue method instantiates a new parser internally.) Then you read the error from the parser that was not used to parse the string.

How to return a raw string of text/json from aspnet mvc and parse it with the iPhone JSON library

I have a web service that returns a raw string of JSON data (sample below)
{'d':{'success':true,'msg':null,'data':[{'productId':'4b7fcb0f818e4a4abaf5b3c78654b631','id':4283}]}}
... And when I attempt to parse this JSON using the popular JSON library for iPhone development I notice a problem in the following method
- (id)objectWithString:(NSString *)repr {
[self clearErrorTrace];
if (!repr) {
[self addErrorWithCode:EINPUT description:#"Input was 'nil'"];
return nil;
}
depth = 0;
c = [repr UTF8String];
id o;
if (![self scanValue:&o]) {
return nil;
}
// more code ...
}
When I hit the last if statement shown I show c to be a valid char (showing the json values inside as expected) but I notice that after o is defined I return nil inside that last if causing this error from the library
#import "NSString+SBJSON.h"
#import "SBJsonParser.h"
#implementation NSString (NSString_SBJSON)
- (id)JSONValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser objectWithString:self];
if (!repr)
NSLog(#"-JSONValue failed. Error trace is: %#", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
#end
Any idea what might be wrong with taking a string of what looks like json and trying to parse it like the below?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray *json = [responseString JSONValue]; //here it all fails
}
Just as a note- this works without error when I query a valid json web service from a large company. My app is aspnet mvc and the return line is simply
return this.Content(jsonStringValue, "text/json");
You should use the built in JSON result object from your action method instead of the Content() method:
return Json(data);
It will automatically serialize your object to be valid JSON.
It would be useful to provide actual error messages/traces.
At any rate, your JSON string is not valid: a string in JSON is quoted within double quotes, not single quotes. The following is valid JSON:
{"d":{"success":true,"msg":null,"data":[{"productId":"4b7fcb0f818e4a4abaf5b3c78654b631","id":4283}]}}
Edit: note that your JSON (top level) data represents an object, not an array. Hence
NSArray *json = [responseString JSONValue];
should be replaced with
NSDictionary *json = [responseString JSONValue];
because SBJSON represents JSON objects as dictionaries.