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.

4

1 回答 1

4

正如您在问题中已经提到的那样,isValidJSONObject

返回一个布尔值,指示给定对象是否可以转换JSON 数据

在您的情况下,您不想创建 JSON 数据,而是使用 JSON 数据创建字典。:

tempDict = [NSJSONSerialization JSONObjectWithData:urlData
                                           options:NSJSONReadingMutableContainers
                                             error:&error];

if (!tempDict) {
  NSLog(@"Error parsing JSON: %@", error);
}
于 2013-05-15T06:50:00.917 回答