[英]How to get boolean value from JSON?
Suppose this is a value in a JSON I want to assign to a BOOL variable:假设这是 JSON 中的一个值,我想分配给一个 BOOL 变量:
"retweeted": false
Here is how I parse JSON data:以下是我如何解析 JSON 数据:
NSError *error;
NSArray *timeline = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
Now, I have a bool property defined as:现在,我有一个 bool 属性定义为:
BOOL *retweeted;
Inside my class. When I do this while parsing the JSON:在我的 class 中。当我在解析 JSON 时这样做:
tweet.retweeted = [[[timeline objectAtIndex:i] objectForKey:@"retweeted"] boolValue];
I get this error:我收到此错误:
How to solve this problem?如何解决这个问题呢?
My preferred way of doing it is:我喜欢的做法是:
BOOL success = [[responseObject valueForKey:@"success"] boolValue]
Clean, succinct and inline.干净、简洁和内联。
BOOL *retweeted;
this is wrong, booleans are scalars, not Objective-C objects, so they don't need to be declared as pointers.这是错误的,布尔值是标量,而不是 Objective-C 对象,因此不需要将它们声明为指针。 Use
采用
BOOL retweeted;
instead.反而。
After serialization with NSJSONSerialization
the boolean is stored as an NSNumber
.使用
NSJSONSerialization
存储为NSNumber
。 If you look at the type it actually stores is is a __NSCFBoolean
but that does not matter.如果您查看它实际存储的类型是
__NSCFBoolean
但这并不重要。 NSNumber
is an abstract class that does not exist. NSNumber
是一个不存在的抽象 class。 The system stores the value with a concrete class.系统将值存储为具体的 class。
So所以
NSNumber* boolean = [serializedDictionary valueForKey:@"boolValue"];
this returns a @0
for NO
and @1
for YES
.这将返回
@0
表示NO
和@1
表示YES
。 You can use is as a booleanValue by doing:您可以通过执行以下操作将 is 用作 booleanValue:
if(boolean.boolValue){
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.