简体   繁体   中英

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 

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 remember that it will work when your objects are simple, like in your example (it have only NSString properties). If you have a more complex object with a some custom classes properties. You have to provide more logic to create that json in that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM