How to convert NSDictionary to custom object

1110 picture 1110 · Jan 24, 2014 · Viewed 21.3k times · Source

I have a json object:

@interface Order : NSObject

@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;

- (NSMutableDictionary *)toNSDictionary;
...

- (NSMutableDictionary *)toNSDictionary
{

    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:self.OrderId forKey:@"OrderId"];
    [dictionary setValue:self.Title forKey:@"Title"];
    [dictionary setValue:self.Weight forKey:@"Weight"];

    return dictionary;
}

In string this is:

{
  "Title" : "test",
  "Weight" : "32",
  "OrderId" : "55"
}

I get string JSON with code:

NSMutableDictionary* str = [o toNSDictionary];

    NSError *writeError = nil;

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Now I need to create and map object from JSON string:

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *e;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];

This returns me filled NSDictionary. What should I do to get object from this dictionary?

Answer

Andrey Gordeev picture Andrey Gordeev · Jan 24, 2014

Add a new initWithDictionary: method to Order:

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
    if (self = [super init]) {
        self.OrderId = dictionary[@"OrderId"];
        self.Title = dictionary[@"Title"];
        self.Weight = dictionary[@"Weight"];    
    }
    return self;    
}

Don't forget to add initWithDictionary's signature to Order.h file

In the method where you get JSON:

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&e];
Order *order = [[Order alloc] initWithDictionary:dict];