简体   繁体   English

如何将模型对象转换为JSON

[英]How to Convert Model Object to JSON

How can i convert model Object to JSON Format Without Using any frameworks ? 如何在不使用任何框架的情况下将模型对象转换为JSON格式?

 @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 : 因此,如果对象看起来像这个modelData("imageName","01.05.2016","name")toJSON方法将为您提供:

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

So the 所以

NSDictionary *dict = [modelObjectInstance toJSON]

gives you NSDictionary with you object. 给您NSDictionary和您的对象。

Then you can get JSON string by : 然后,您可以通过以下方式获取JSON字符串:

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). 请记住,当您的对象很简单时,它将起作用,例如您的示例(它仅具有NSString属性)。 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. 您必须提供更多逻辑以这种方式创建该json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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