我正在使用 NSJSONSerialization dataWithJSONObject 将我的类序列化为 JSON。当它序列化一个 BOOL 时,它会在 JSON 字符串中为其提供值 1 或 0。我需要这是真或假。这可以通用吗?
最佳答案
当我创建 [NSNumber numberWithBool:NO]
时,NSJSONSerialization 在 JSON 字符串中返回单词“false”。
编辑通过新的快捷方式,您还可以使用这些方便的人:
@(YES) / @(NO)
@(1) / @(0)
@YES / @NO
@1 / @0
这样你可以避免循环遍历你的值之类的事情。我想要完全相反的行为,但有 NSNumber
对象。所以我必须循环......
编辑二
mbi在评论中指出iOS版本之间存在差异。所以这里是一个 iOS9 测试:
NSDictionary *data = @{
@"a": @(YES),
@"b": @YES,
@"c": @(1),
@"d": @1
};
NSLog(@"%@", [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:data options:0 error:nil] encoding:NSUTF8StringEncoding]);
2016-07-05 02:23:43.964 Test App[24581:6231996] {"a":true,"b":true,"c":1,"d":1}
https://stackoverflow.com/questions/13615451/