iOS 中JSONModel的使用

來源:互聯網
上載者:User

標籤:協議   etc   pcl   man   integer   att   val   nsnumber   lob   

涉想你的JSON資料像這樣:

{ "id": "10", "country": "Germany", "dialCode": 49, "isInEurope": true }
  • 為你的資料模型建立一個Objective-C的類,繼承自JSONModel.
  • 將JSON中的keys在.h檔案中聲明為屬性:
#import "JSONModel.h"@interface CountryModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* country;@property (strong, nonatomic) NSString* dialCode;@property (assign, nonatomic) BOOL isInEurope;@end

在.m檔案中不需要做任何事情.

  • 用資料初始化你的model:
#import "CountryModel.h"...NSString* json = (fetch here JSON from Internet) ...NSError* err = nil;CountryModel* country = [[CountryModel alloc] initWithString:json error:&err];
舉個例子命名自動匹配
{  "id": "123",  "name": "Product name",  "price": 12.95}
@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* name;@property (assign, nonatomic) float price;@end@implementation ProductModel@end
模型嵌套 (模型包含其他模型)
{  "order_id": 104,  "total_price": 13.45,  "product" : {    "id": "123",    "name": "Product name",    "price": 12.95  }}@interface OrderModel : JSONModel@property (assign, nonatomic) int order_id;@property (assign, nonatomic) float total_price;@property (strong, nonatomic) ProductModel* product;@end@implementation OrderModel@end
模型集合
{  "order_id": 104,  "total_price": 103.45,  "products" : [    {      "id": "123",      "name": "Product #1",      "price": 12.95    },    {      "id": "137",      "name": "Product #2",      "price": 82.95    }  ]}
@protocol ProductModel@end@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* name;@property (assign, nonatomic) float price;@end@implementation ProductModel@end@interface OrderModel : JSONModel@property (assign, nonatomic) int order_id;@property (assign, nonatomic) float total_price;@property (strong, nonatomic) NSArray<ProductModel>* products;@end@implementation OrderModel@end

注意: 角括弧後 NSArray 包含一個協議. 這跟Objective-C原生的泛型不是一個概念. 他們不會衝突, 但對於JSONModel來說,協議必須在一個地方聲明.

key映射
{  "order_id": 104,  "order_details" : [    {      "name": "Product#1",      "price": {        "usd": 12.95      }    }  ]}@interface OrderModel : JSONModel@property (assign, nonatomic) int id;@property (assign, nonatomic) float price;@property (strong, nonatomic) NSString* productName;@end@implementation OrderModel+(JSONKeyMapper*)keyMapper{  return [[JSONKeyMapper alloc] initWithDictionary:@{    @"order_id": @"id",    @"order_details.name": @"productName",    @"order_details.price.usd": @"price"  }];}@end
設定全域鍵映射(應用於所有model)
[JSONModel setGlobalKeyMapper:[    [JSONKeyMapper alloc] initWithDictionary:@{      @"item_id":@"ID",      @"item.name": @"itemName"   }]];
設定底線自動轉駝峰
{  "order_id": 104,  "order_product" : @"Product#1",  "order_price" : 12.95}
@interface OrderModel : JSONModel@property (assign, nonatomic) int orderId;@property (assign, nonatomic) float orderPrice;@property (strong, nonatomic) NSString* orderProduct;@end@implementation OrderModel+(JSONKeyMapper*)keyMapper{  return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];}@end
可選屬性 (就是說這個屬性可以為null或者為空白)
{  "id": "123",  "name": null,  "price": 12.95}
@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString<Optional>* name;@property (assign, nonatomic) float price;@property (strong, nonatomic) NSNumber<Optional>* uuid;@end@implementation ProductModel@end
忽略屬性 (就是完全忽略這個屬性)
{  "id": "123",  "name": null}@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString<Ignore>* customProperty;@end@implementation ProductModel@end
設定所有的屬性為可選(所有屬性值可以為空白)
@implementation ProductModel+(BOOL)propertyIsOptional:(NSString*)propertyName{  return YES;}@end
使用JSONModel內建的 HTTP 要求
//add extra headers[[JSONHTTPClient requestHeaders] setValue:@"MySecret" forKey:@"AuthorizationToken"];//make post, get requests[JSONHTTPClient postJSONFromURLWithString:@"http://mydomain.com/api"                                   params:@{@"postParam1":@"value1"}                               completion:^(id json, JSONModelError *err) {                                   //check err, process json ...                               }];
將model轉化為字典或者json格式的字串
ProductModel* pm = [[ProductModel alloc] initWithString:jsonString error:nil];pm.name = @"Changed Name";//convert to dictionaryNSDictionary* dict = [pm toDictionary];//convert to textNSString* string = [pm toJSONString];
自訂資料的轉換
@implementation JSONValueTransformer (CustomTransformer)- (NSDate *)NSDateFromNSString:(NSString*)string {    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    [formatter setDateFormat:APIDateFormat];    return [formatter dateFromString:string];}- (NSString *)JSONObjectFromNSDate:(NSDate *)date {    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];    [formatter setDateFormat:APIDateFormat];    return [formatter stringFromDate:date];}@end
自訂處理指定的屬性
@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* name;@property (assign, nonatomic) float price;@property (strong, nonatomic) NSLocale *locale;@end@implementation ProductModel// Convert and assign the locale property- (void)setLocaleWithNSString:(NSString*)string {    self.locale = [NSLocale localeWithLocaleIdentifier:string];}- (NSString *)JSONObjectForLocale {    return self.locale.localeIdentifier;}@end
自訂JSON校正
@interface ProductModel : JSONModel@property (assign, nonatomic) int id;@property (strong, nonatomic) NSString* name;@property (assign, nonatomic) float price;@property (strong, nonatomic) NSLocale *locale;@property (strong, nonatomic) NSNumber <Ignore> *minNameLength;@end@implementation ProductModel- (BOOL)validate:(NSError *__autoreleasing *)error {    BOOL valid = [super validate:error];    if (self.name.length < self.minNameLength.integerValue) {        *error = [NSError errorWithDomain:@"me.mycompany.com" code:1 userInfo:nil];        valid = NO;    }    return valid;}@end

iOS 中JSONModel的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.