Obj-C:将对象数组转换为NSDictionary以与JSONRepresentation一起使用

时间:2011-08-20 00:22:07

标签: 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" }
               ]
}

1 个答案:

答案 0 :(得分:3)

为每个返回该特定对象字典的自定义类写一个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];