Search code examples
objective-cjsonnsjsonserialization

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.


Solution

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