使用NSJSONSerialization JSONObjectWithData解析JSON字符串的真值和假值:

时间:2021-10-06 01:05:48

I'm developing an iOS 5 and above application with latest SDK.

我正在用最新的SDK开发一个ios5及以上的应用程序。

I have to parse this JSON:

我必须解析这个JSON:

{"GetHoroscope":false,"GetQuoteOfTheDay":false, ... }

To do it, I have this code:

为此,我有以下代码:

- (NSDictionary*)getDictionaryFromNSData:(NSData*)jsonData
{
    NSError* error = nil;
    id jsonObject = [NSJSONSerialization
                     JSONObjectWithData:jsonData
                     options:NSJSONReadingAllowFragments
                     error:&error];
    if ((jsonObject != nil) && (error == nil))
    {
        NSLog(@"Successfully deserialized...");
        if ([jsonObject isKindOfClass:[NSDictionary class]])
        {
            NSDictionary* deserializedDictionary = (NSDictionary *)jsonObject;
            NSLog(@"Dersialized JSON Dictionary = %@", deserializedDictionary);

            return deserializedDictionary;
        }
    }

    return nil;
}

But I have a problem with boolean values. When I check deserializedDictionary I see that GetHoroscope and GetQuoteOfTheDay values are null.

但是我有布尔值的问题。当我检查deserializedDictionary时,我发现GetHoroscope和GetQuoteOfTheDay值为空。

Do I need to do something special with boolean values?

我需要对布尔值做一些特殊的处理吗?

1 个解决方案

#1


9  

JSON "true" and "false" values are stored as NSNumber objects, so the following should work:

JSON“true”和“false”值存储为NSNumber对象,因此下面应该工作:

BOOL b = [deserializedDictionary[@"GetHoroscope"] boolValue];

#1


9  

JSON "true" and "false" values are stored as NSNumber objects, so the following should work:

JSON“true”和“false”值存储为NSNumber对象,因此下面应该工作:

BOOL b = [deserializedDictionary[@"GetHoroscope"] boolValue];