开发者

Obj-C: Convert an Array of objects into an NSDictionary for use with JSONRepresentation

开发者 https://www.devze.com 2023-03-29 04:14 出处:网络
I have a开发者_如何学Gon NSMutableArray of custom objects with various information them. For instance the object might contain:

I have a开发者_如何学Gon NSMutableArray of custom objects with various information them. For instance the object might contain:

firstname
lastname
email

I'd like to be able to add these objects to an NSDictionary, so that I can call SBJSON's 'JSONRepresentation' Function, and the final JSON format would look like:

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


Write a dictionaryRepresentation for each of your custom classes that returns a dictionary for that particular object. Then you can do something like this:

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消