我正在尝试在 Objective-C 中使用 POST 发送 JSON 数据。
我有两个 NSDictionary ,我想把第一个 NSDictionary**(json_dst)** 放到第二个 NSDictionary**(json)** 中。
我尝试了下面的代码,但它似乎不正确......
NSString DEVICE_UUID = @"9c88da0c-5362-460b-8647-590a981d912e";
int command = 65536;
NSDictionary *json_dst = [NSDictionary dictionaryWithObjectsAndKeys:@"type", @"Device",@"uuid",DEVICE_UUID, nil];
NSDictionary *json = [NSDictionary dictionaryWithObjectsAndKeys:@"id",@"200",@"dst",json_dst,@"msgType",@"MESSAGE",@"msg",command, nil];
它将在 NSDictionary *json = [NSDictionary dictionaryWithObjectsAndKeys:@"id",@"200",@"dst",json_dst,@"msgType",@"MESSAGE",@"msg"时崩溃命令,无];
。
错误日志是
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid (non-string) key in JSON dictionary'
但我不知道原因...
有人可以教我怎么做吗?我错过了什么吗?
提前致谢。
最佳答案
首先,您的键和对象的顺序错误。
其次,您试图将原始类型放入字典中(命令是一个 int)。字典必须包含 Objective-C 实例,从 NSObject 继承。
最后,您的 DEVICE_UUID 缺少指针星号 (*)。
为了使字典更易于使用并使其保持键值顺序,我将使用 modern Objective-C literals 进行展示。 .
不是直接将原语放入,而是需要将其包装在 NSNumber 中。这可以通过“装箱”@(command)
中的数字来完成,这是文字的另一个特征。
NSString *DEVICE_UUID = @"9c88da0c-5362-460b-8647-590a981d912e";
int command = 65536;
NSDictionary *json_dst = @{@"type":@"Device", @"uuid":DEVICE_UUID};
NSDictionary *json = @{@"id":@"200", @"dst":json_dst, @"msgType":@"MESSAGE", @"msg":@(command)};
关于ios - 如何将 JSON 数据放入 Objective-C 中的另一个 JSON 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26038995/