Skip to content
This repository was archived by the owner on Aug 30, 2019. It is now read-only.

Deserialization of Arrays

pashields edited this page Jan 29, 2012 · 2 revisions

In addition to handling dictionaries, ClassMapper also supports (de)serialization of arrays. If you've followed along with dictionaries, most of this will be pretty obvious.

Deserializing an array of your objects

Let's say that you have a user class:

@interface User : NSObject
@property(nonatomic, strong)NSString *name;
@property(nonatomic, strong)NSString *id;
@end

Let's say you called an API and got a list of a user's friends, you'd end up with an object like the one created with:

// Equivalent to [{"name":"Macready","id":"1"}, {"name":"Blair","id":"2"}, {"name":"Childs","id":"3"}]
NSArray *cereal = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"Macready", @"name", @"1", @"id", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:@"Blair", @"name", @"2", @"id", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:@"Childs", @"name", @"3", @"id", nil],
                          nil];

If we want to deserialize this into an NSArray of User instances, the call is very similar to a single object:

NSArray *users = [ClassMapper deserialize:cereal toClass:[User class]];
User *macready = [users objectAtIndex:0];
macready.name; // @"Macready"

Obviously, this prohibits the use of mixed type arrays. For now, if you want to deserialize those, you'll have to manually deserialize each element of the array based on some known schema.

Arrays inside objects

Let's say we have a class with only one property, an NSArray:

@interface UserList : NSObject
@property(nonatomic, strong)NSArray *users;
@end

We know that arrays don't have any type information, so we'll have to use the MapperConfig again. Unlike with dictionaries, we specify type information for arrays at the array level. It looks like this:

[[MapperConfig sharedInstance] mapKey:@"users" toClass:[User class]]
NSDictionary *cerealObj = [NSDictionary dictionaryWithObject:cereal forKey:@"users"];
UserList *userList = [ClassMapper deserialize:cerealObj toClass:[UserList class]];
User *macready = [userList.users objectAtIndex:0];
macready.name; // @"Macready"

And that's really it. This strategy will also work for nested arrays, so you could easily deserialize a two dimensional array of NSDictionaries into a two dimensional array of Coordinate instances.

Clone this wiki locally