views:

33

answers:

1

I have some python code for Google App Engine that responds with the string {"sample_list": [{"message": "Hello, world.", "name": "Human"}]} I am using this JSON-framework developed by sbrautaset to convert the string to an object that I can use (NSDictionary in this case). I am following the tutorial here to use the framework.

My problem is that I am getting null for [jsonParser objectWithString:jsonString error:NULL] where jsonString is {"sample_list": [{"message": "Hello, world.", "name": "Human"}]} and jsonParser is an instance of SBJSON from the framework.

I am guessing that the parser is not recognizing the string as a JSON format. Any insight would be appreciated, as I am completely new to JSON.

Thank you!

UPDATE: The Server Side Python Code

outer_dict = {}
middle_list = []
inner_dict = {}
inner_dict["name"] = "Human"
inner_dict["message"] = "Hello, world."
middle_list.append(inner_dict)
outer_dict["sample_list"] = middle_list
json_message = simplejson.dumps(outer_dict)
self.response.out.write(json_message)

The Client Side Objective-C Code

NSURL *url = [NSURL URLWithString:@"http://theurl"];
NSString *jsonString = [self stringWithUrl:url];
NSLog(@"%@", jsonString);
id myObj = [jsonString JSONValue];
NSLog(@"%@", myObj);

stringWithUrl

- (NSString *) stringWithUrl:(NSURL *)url {
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                            cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                        timeoutInterval:30];
NSData *urlData;
NSURLResponse *response;
NSError *error; 

urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

    return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
}
+1  A: 

Hey, remove the inner {}

{"sample_list": ["message": "Hello, world.", "name": "Human"]}

You should use a JSON encoder on the server side to encode objects into JSON strings. This way you won't mistakenly produce invalid strings.

Brad Goss
Thank you for your response. I'm using Python's simplejson to encode my objects to JSON strings. I had the inner {}, because I will ultimately have a list of dictionaries. Would this cause a problem?
ayanonagon
Ok, your right to use the inner {} then. Strange... The string appears valid. Catch the error, instead of passing error:NULL passNSError *error = nil;[jsonParser objectWithString:jsonString error:NSLog(@"%@", error);This may help diagnose the problem.
Brad Goss
Thank you, I just did what you suggested, and I got Error Domain=org.brautaset.JSON.ErrorDomain Code=3 "Unrecognised leading character" I am not sure what this is referring to, since the string looks fine.
ayanonagon
When I convert my JSON strings into objects, I use the following: id myObj = [jsonString JSONValue]; Try using that method instead. Log your jsonString too. Make sure the string is what your expecting it to be and not a "server error" message.
Brad Goss
Hmmm. I am still getting "Unrecognised leading character," and I double checked that my string actually says {"sample_list": [{"message": "Hello, world.", "name": "Human"}]}
ayanonagon
I just copied and was able to parse that string. Maybe there is a hidden character? Could you post the code that is encoding (server side) and decoding (client side)?
Brad Goss
Instead of calling the URL to get the string (which looks formatted correctly to me), I explicitly declared NSString *string = @"{\"sample_list\": [{\"message\": \"Hello, world.\", \"name\": \"Human\"}]}"; id myObj = [string JSONValue]; NSLog(@"%@", myObj);And that works for some reason... I don't see how the two strings are any different :/
ayanonagon
Oh haha, I just did what you did without knowing.
ayanonagon
This is the Python code I have in GET that encodes the objectouter_dict = {} middle_list = [] inner_dict = {} inner_dict["name"] = "Human" inner_dict["message"] = "Hello, world." middle_list.append(inner_dict) outer_dict["sample_list"] = middle_list json_message = simplejson.dumps(outer_dict) self.response.out.write(json_message)
ayanonagon
I updated the question statement since the code is hard to read in the comments. Thanks again.
ayanonagon
Can you post the method [self stringWithUrl:url];
Brad Goss
Alright, i've gone as far as to replicate your code in an app with a server. It works. Other than the method stringWithUrl, everything else seems ok. I bet your encoding is wrong. Are you using NSUTF8StringEncoding?
Brad Goss
Yup, that is the encoding that I am using.
ayanonagon
I used that method and it worked too!!! Arg. Strange. Try fetching the data from the server with this line NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error: On a side note, there are a couple issues with that method. When passing variables by reference ( NSError *error = nil; And your returning string is leaked. You want return [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding] autorelease];
Brad Goss
Really!! Wow. Let me know if you find the source of the line break.
Brad Goss
Wow, I just got rid of all of my print statements from the GET method. I had no idea that they could affect the response. Thanks for your help!!!
ayanonagon