【问题标题】:Create nested JSON in Objective-C在 Objective-C 中创建嵌套 JSON
【发布时间】:2015-02-01 16:50:31
【问题描述】:

我正在尝试创建如下所示的 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];

但是,这不起作用。我在这里做错了什么?

【问题讨论】:

  • 访问 json.org 并学习 JSON 语法。学习只需5-10分钟。然后你会意识到你缺少一个 JSON 数组。

标签: objective-c json nsdictionary


【解决方案1】:

您的代码的第一行无法编译,因此您需要修复它。

您的示例输出中“类别”的值是一个包含一个元素的数组,恰好是一个字典。所以你需要

NSDictionary* oneCategory = [NSDictionary dictionaryWithObjectsAndKeys:...];
NSArray* categories = [NSArray arrayWithObject:oneCategory];
[req setObject:categories forKey:@"categories"];

而且你真的应该使用更现代的语法,比如

req [@"categories"] = @[oneCategory];

【讨论】:

    【解决方案2】:

    你缺少一个数组:

    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];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多