Parsing JSON value in objective c error? - objective-c

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.

Related

Replace " in string with \"

I am trying to send a string to the server. I encode it and set it as the body of an HTTP request using
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
Where body is the string.It has to be in json format.
For example
body = [NSString stringWithFormat:#"{\"emailBody\":\"%#\"}",string] ;
should be valid
But i accept string from user and it may contain double quotes.Therefore i have to escape double quotes(") in it.
For example if want to send just one "
{\"emailBody\":\"\\\"\"}
(harddcoded) returns positive response from server.
So i would like to create such a string from the original string.I tried the following
string = [string stringByReplacingOccurencesOfString:#"\"" withString:#"\\\\\""];
But it did not work.I got \" in my test email.Thats as far as i have been able to get.
Am I taking the right approach ??I would appreciate it if someone would point me in the right direction.Thanks
You should generate your JSON directly from a dictionary. That'll take care of all the encoding automatically for you:
NSDictionary *body = #{#"emailBody": string};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[request setHTTPBody:jsonString];
}

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];
}

Issue with parsing JSON data

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);
}

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

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.