【问题标题】:Keyless NSDictionary from NSArray来自 NSArray 的无键 NSDictionary
【发布时间】:2013-11-27 09:34:50
【问题描述】:

我正在尝试创建看起来像的 JSON

[
   {
      property1 = "test1",
      property2 = "test2",
   },
   {
      property1 = "test1",
      property2 = "test2",
   },
   ...
]

到目前为止,我使用 NSDictionary 所能得到的只是:

[
   key1 = {
      property1 = "test1",
      property2 = "test2",
   },
   key 2 = {
      property1 = "test1",
      property2 = "test2",
   },
   ...
]

... 这不好。有没有简单的方法在 NSDictionary 中创建无键数组?

【问题讨论】:

  • 那是什么类型的?您使用的是什么 JSON 编码器?你能告诉我们你从 JSON 中得到什么的反序列化代码 + NSLog 类型吗
  • 告诉我你创建这个 JSON 的代码
  • “无钥匙字典”只不过是NSSet...没有意义

标签: ios objective-c json cocoa nsdictionary


【解决方案1】:

试试:

NSArray *objects = @[
    @{ @"property1": @"test1", @"property2": @"test2" },
    @{ @"property1": @"test1", @"property2": @"test2" }
];

NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:objects options:0 error:&error];

看起来您使用NSDictionary 作为根对象,而不是NSArray

【讨论】:

    【解决方案2】:

    您的 JSON 无效。它应该是这样的 JSON 数组:

    [
       {
          property1 : "test1",
          property2 : "test2",
       },
       {
          property1 : "test1",
          property2 : "test2",
       },
       ...
    ]
    

    或嵌入了其他对象的 JSON 对象,但在这种情况下,您需要指定属性的名称:

    {
       obj1 : {
          property1 : "test1",
          property2 : "test2",
       },
       obj2 : {
          property1 : "test1",
          property2 : "test2",
       },
       ...
    }
    

    第一种情况映射到 NSDictionaries 的 NSArray,而第二种情况映射到具有两个键 (obj1, obj2,) 的 NSDictionary,每个映射到具有两个键 (property1, property2) 的 NSDictionary。

    从对您的问题所做的编辑来看,您需要序列化此对象,以获得所需的结构:

    NSArray * dataForJSON = @[
        @{
             @"property1" : @"test1", 
             @"property2" : @"test2"
         },        
        @{
             @"property1" : @"test1", 
             @"property2" : @"test2"
         }
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多