简体   繁体   English

找出值是否来自JSON是布尔值(true / false)

[英]find out if value fron a JSON was a boolean (true/false)

I'm coding a category on NSManagedObject so it can populates its attributes itself from a NSDictionnary I have from a JSON (via NSJSONSerialization) 我在NSManagedObject上编码一个类别,因此它可以从我从JSON获得的NSDictionnary本身(通过NSJSONSerialization)填充其属性

My problem is: if the original value is true or false, it is converted to NSNumber, but I want to insert it in the managed object as a BOOL (I'm aware of boolValue) if, and only if it was originally a BOOL and not a number. 我的问题是:如果原始值是true或false,则将其转换为NSNumber,但如果且仅当它最初是BOOL时,我想将其作为BOOL插入到托管对象中(我知道boolValue)而不是数字。 So far, my related code is : 到目前为止,我的相关代码是:

if ([value isKindOfClass:[NSNumber class]])
        {
            if (NSClassFromString(@"__NSCFBoolean") && [value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
                [self setValue:[NSNumber numberWithBool:[value boolValue]] forKey:key];
            } else if (NSClassFromString(@"NSCFBoolean") && [value isKindOfClass:NSClassFromString(@"NSCFBoolean")]) {
                [self setValue:[NSNumber numberWithBool:[value boolValue]] forKey:key];
            } else {
                [self setValue:value forKey:key];
            }
        }

I get the error : 我得到错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myJsonOriginalKeyName 由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类与键myJsonOriginalKeyName的键值编码兼容

Again, my managed object has a boolean attribute for the corresponding key when it's value id true/false in the original JSON How can I automatically determine if I should convert value to a BOOL or NSNumber 同样,我的托管对象在原始JSON中值为ID true / false时,具有对应键的布尔属性,该如何自动确定将值转换为BOOL还是NSNumber

I am doing this right now in my app, its sort of - well - not completely sanctioned, but it seems to work just fine using NSJSONSerialization in iOS7: 我现在正在我的应用程序中执行此操作,虽然-完全-尚未完全批准,但使用iOS7中的NSJSONSerialization似乎可以正常工作:

if(strcmp([num objCType], "c") == 0) {
   // its a boolean
   ...

The caveat us that Apple says in the Class Description that you cannot count on this to be consistent. 苹果在类说明中说的告诫我们,您不能指望这一点是一致的。 That said, if NSJSONSerialization is only using a method to convert bools that results in this type, it probably won't change any time soon. 就是说,如果NSJSONSerialization只使用一种方法来转换导致这种类型的布尔值,那么它可能不会很快改变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM