我正在尝试创建如下所示的JSON:
{
"id": "feed/http://feeds.feedburner.com/design-milk",
"title": "Design Milk",
"categories": [
{
"id": "user/category/test",
"label": "test"
}
]
}
我正在使用这种方法:
NSMutableDictionary *req = [NSMutableDictionary @"feed/http://feeds.feedburner.com/design-milk" forKey:@"id"];
[req @"Design Milk" forKey:@"title"];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
@"user/category/test", @"id", @"test", @"label",
nil];
[req setObject:tmp forKey:@"categories"];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:req options:0 error:&error];
但是,这不起作用。我在这里做错了什么?
答案 0 :(得分:0)
您的代码的第一行不会编译,因此您需要修复它。
"类别"的价值在您的示例输出中是一个包含一个元素的数组,它恰好是一个字典。所以你需要
NSDictionary* oneCategory = [NSDictionary dictionaryWithObjectsAndKeys:...];
NSArray* categories = [NSArray arrayWithObject:oneCategory];
[req setObject:categories forKey:@"categories"];
你应该使用更现代的语法,比如
req [@"categories"] = @[oneCategory];
答案 1 :(得分:0)
你错过了一个数组:
NSMutableDictionary *req =[NSMutableDictionary dictionaryWithObjectsAndKeys:@"feed/http://feeds.feedburner.com/design-milk", @"id", nil];
req[@"title"] = @"Design Milk";
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
@"user/category/test", @"id",
@"test", @"label",
nil];
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:tmp];
[req setObject:arr forKey:@"categories"];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:req options:0 error:&error];