3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jamesla
  • 1,378
  • 7
  • 31
  • 62
  • 1
    IsValidJsonObject sounds like the wrong method. Sounds like it is checking the object before converting it to data. You want it the other way round. – Fogmeister May 15 '13 at 06:24
  • @Fogmeister: You're probably right. Seems to me, though, that in that case `isValidJSONObject` should always return true. (What keeps an NSString from being JSON-serializable?) – cHao May 15 '13 at 15:20
  • urlData is an NSData object. You cannot encode an NSData object into JSON data. He is checking for encoding the object. He needs to check for decoding the object. – Fogmeister May 15 '13 at 15:21

1 Answers1

4

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);
}
tilo
  • 14,009
  • 6
  • 68
  • 85