NSJSONSerialization返回零

时间:2013-04-16 18:01:41

标签: iphone ios json web-services nsdata

{"User":{"id":"42","name":"martin"}}

将我的NSData转换为NSString会返回这个看似完全有效的JSON,但方法是:

[NSJSONSerialization isValidJSONObject:data]

说这不是一个有效的JSON对象。

有人能指出我犯过的错误,或者想到这种情况发生的原因吗?

1 个答案:

答案 0 :(得分:9)

我打赌你的字符串中有一个不可打印的字符,例如,使数据无效。

声明NSError* error变量,然后调用[NSJSONSerialization JSONObjectWithData:data options:0 error:&error]方法尝试转换JSON:显然,如果您的数据被视为无效,它将返回nil,但至少您将拥有之后描述NSError* error变量中的错误。

NSData* data = ... // your data
NSError* error = nil; // Declare a variable to hold the error upon return
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error]; // Try to convert your data
NSLog(@"obj: %@ ; error: %@", error); // Log the decoded object, and the error if any