【问题标题】:Obj-C: Convert an Array of objects into an NSDictionary for use with JSONRepresentationObj-C:将对象数组转换为 NSDictionary 以与 JSONRepresentation 一起使用
【发布时间】:2011-08-20 00:22:06
【问题描述】:

我有一个包含各种信息的自定义对象的 NSMutableArray。 例如,该对象可能包含:

firstname
lastname
email

我希望能够将这些对象添加到 NSDictionary,这样我就可以调用 SBJSON 的 'JSONRepresentation' 函数,最终的 JSON 格式如下所示:

{
    "Users" : [
               { "user1First" : "FirstName",
                 "user1Last"  : "LastName",
                 "user1Email" : "Email" },
               { "user2First" : "FirstName",
                 "user2Last"  : "LastName",
                 "user2Email" : "Email" },
               { "user3First" : "FirstName",
                 "user3Last"  : "LastName",
                 "user3Email" : "Email" }
               ]
}

【问题讨论】:

  • 我认为您应该进一步澄清这个问题。您是否尝试生成许多与“FirstName”等具有相同值的用户?我不太了解,无法提供帮助。
  • “FirstName”、“LastName”和“Email”是 JSON 值的键。

标签: objective-c json nsmutablearray nsdictionary sbjson


【解决方案1】:

为每个自定义类编写一个dictionaryRepresentation,以返回该特定对象的字典。然后你可以这样做:

NSMutableArray *dictionaryArray = [NSMutableArray arrayWithCapacity:yourOtherArray.count];
for (id object in yourOtherArray) {
    [dictionaryArray addObject:[object dictionaryRepresentation]];
}
// not sure what SBJSON's function returns so I'm using id here
id JSONRepresentation = [dictionaryArray JSONRepresentation];

【讨论】:

  • 我会使用id object,而不是NSObject *object。这将阻止警告。
  • 好主意。编辑反映。
  • dictionaryRepresentation iOS6 及以上
猜你喜欢
  • 2017-03-08
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多