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