rob*_*ect 7 macos cocoa json objective-c
我无法找到如何key:true在我的NSDictionary中插入一个布尔值(在JSON字符串中显示):
NSMutableDictionary* jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue: YES forKey: @"key"];
Run Code Online (Sandbox Code Playgroud)
上面的代码没有运行(显然因为YES不是对象).
我怎么能做到这一点?
Jer*_*man 11
您可以使用,将布尔值插入字典中NSNumber.在这种情况下,您可以@YES直接使用文字表达式和字典文字,使其成为一个单行:
NSDictionary *jsonDict = @{@"key" : @YES};
Run Code Online (Sandbox Code Playgroud)
要将其编码为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];
}
Run Code Online (Sandbox Code Playgroud)
使用Objective-C文字,[NSNumber numberWithBool:YES]可以用@YES表示,
你可以这样创建你的字典:
NSDictionary *jsonDict = @{@"key":@YES};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9526 次 |
| 最近记录: |