Rinto Andrews Rinto Andrews - 4 months ago 22
JSON Question

How to Convert Model Object to JSON

How can i convert model Object to JSON Format Without Using any frameworks ?



@interface modelData : NSObject

// store name
@property(nonatomic,strong) NSString *name;

// store release date
@property(nonatomic,strong) NSString *releaseDate;

//store image
@property(nonatomic,strong)NSString *image;

// init with local json
-(instancetype)initWithName :(NSString*)name withReleaseDate:(NSString*)releaseDate withImage:(NSString*)imageName;

@end




Answer

To do this without other frameworks you can create some method like :

- (NSDictionary *)toJSON {
    return @{
        @"image" : self.image,
        @"releaseDate" : self.releaseDate,
        @"name" : self.name
    };
}

So if object looks like this modelData("imageName","01.05.2016","name") the toJSON method gives you :

{ "image" : "imageName", "releaseDate" : "01.05.2016", "name" : "name" }

So the

NSDictionary *dict = [modelObjectInstance toJSON]

gives you NSDictionary with you object.

Then you can get JSON string by :

NSData *data = [NSJSONSerialization dataWithJSONObject:dict
                                                   options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                     error:&error];
if (! data) {
    NSLog(@"Error: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

Important

Please remeber that it will work when you object is simple, like in your example (it have only NSString properties). If you have more complex object with some custom classes properties. You have to provide more logic to create that json in that way.

Comments