我找不到如何在NSDictionary中插入布尔值(在JSON字符串中显示为key:true
):
NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: @"key"];
上述代码无法运行(显然是因为YES不是一个对象)。 我该如何解决这个问题?
我找不到如何在NSDictionary中插入布尔值(在JSON字符串中显示为key:true
):
NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: @"key"];
使用NSNumber
将布尔值插入字典中。在这种情况下,您可以直接使用文字表达式@YES
,与字典文字一起使用,使其成为单行:
NSDictionary *jsonDict = @{@"key" : @YES};
要将其编码为JSON格式,请使用+[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:]是将布尔值添加到NSDictionary的典型方式。
使用Objective-C字面量,[NSNumber numberWithBool:YES]可以直接表示为@YES。
你可以这样创建你的字典:
NSDictionary *jsonDict = @{@"key":@YES};