开发者

Objective-C: How to put boolean values in JSON dictionary?

开发者 https://www.devze.com 2023-01-20 16:35 出处:网络
I could not find out how to insert a boolean value (to appear as key:true in the J开发者_如何学PythonSON string) in my NSDictionary:

I could not find out how to insert a boolean value (to appear as key:true in the J开发者_如何学PythonSON string) in my NSDictionary:

NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: @"key"];

The code above does not run (obviously because YES is not an object).

How can I accomplish this?


You insert booleans into a dictionary using NSNumber. In this case, you can use the literal expression @YES directly, together with a dictionary literal, to make this a one-liner:

NSDictionary *jsonDict = @{@"key" : @YES};

To encode it to JSON, use +[NSJSONSerialization dataWithJSONObject:options:error]:

NSError *serializationError;
NSData *jsonData = [NSJSONSerialization
                    dataWithJSONObject:jsonDict
                    options:0 error:&serializationError];
if (!jsonData) {
    NSLog(@"%s: error serializing to JSON: object %@ - error %@",
          __func__, jsonDict, serializationError];
}


+[NSNumber numberWithBool:] is the typical way to add a boolean to a NSDictionary.


With Objective-C literals, [NSNumber numberWithBool:YES] can be represented with just @YES,

You can create your dictionary like so:

    NSDictionary *jsonDict = @{@"key":@YES};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号