objective-c - 对象-C : Convert an Array of objects into an NSDictionary for use with JSONRepresentation

标签 objective-c json nsmutablearray nsdictionary sbjson

我有一个自定义对象的 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" }
               ]
}

最佳答案

为每个自定义类编写一个 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];

关于objective-c - 对象-C : Convert an Array of objects into an NSDictionary for use with JSONRepresentation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7128693/

相关文章:

ios - 使用 Objective-C 从 IOS 上的提醒中打开我的应用程序

javascript - 将 JSON 数据与 JavaScript 对象匹配

ios - NSMutableArray NSLog 输出不同的结果

ios - NSMutablearray 删除对象也删除其他 NSMutablearray 中的对象

ios - 从看起来像的同一个类调用方法

ios - 无法在以编程方式创建的自定义 View 中更改 UILabel 文本值

iphone - EXC_BAD_ACCESS 如果我直接调用 Objective-C block

json - Jackson JSON 动态忽略属性

objective-c - Objective C - 数据绑定(bind)?

ios - 如何检查数组中是否有重复值?