[英]How to Convert Model Object to JSON
如何在不使用任何框架的情況下將模型對象轉換為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
要在沒有其他框架的情況下執行此操作,可以創建一些方法,例如:
- (NSDictionary *)toJSON {
return @{
@"image" : self.image,
@"releaseDate" : self.releaseDate,
@"name" : self.name
};
}
因此,如果對象看起來像這個modelData("imageName","01.05.2016","name")
則toJSON
方法將為您提供:
{ "image" : "imageName", "releaseDate" : "01.05.2016", "name" : "name" }
所以
NSDictionary *dict = [modelObjectInstance toJSON]
給您NSDictionary
和您的對象。
然后,您可以通過以下方式獲取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];
}
重要
請記住,當您的對象很簡單時,它將起作用,例如您的示例(它僅具有NSString
屬性)。 如果您有一個帶有一些自定義類屬性的更復雜的對象。 您必須提供更多邏輯以這種方式創建該json。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.