Use of Jsonmodel in IOS

Source: Internet
Author: User

Think of your JSON data like this:

{"id": "Ten", "Country": "Germany", "Dialcode": $, "Isineurope": true}
    • Create a Objective-c class for your data model, inherited from Jsonmodel.
    • The keys in JSON are declared as attributes in the. h file:
#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

There is no need to do anything in the. m file.

    • Initialize your model with data:
#import "CountryModel.h" ... nsstring* JSON = (fetch here JSON from the Internet) ... nserror* err = nil; countrymodel* country = [[Countrymodel alloc] Initwithstring:json error:&err];
For example, name auto-match.
{  "id": "123",  "name": "Product name",  "price": 12.95}
@interface Productmodel:jsonmodel@property (assign, nonatomic) int id; @property (strong, nonatomic) nsstring* name; @pro Perty (assign, nonatomic) float price; @end @implementation Productmodel@end
Model nesting (model contains other models)
{  "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
Model Collection
{  "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

Note: The angle brackets NSArray are followed by a protocol. This is not a concept with objective-c native generics. They will not clash, but for Jsonmodel, the agreement must be declared in one place.

Key mappings
{  "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
Set Global key mappings (applies to all model)
[Jsonmodel setglobalkeymapper:[    [Jsonkeymapper alloc] initwithdictionary:@{      @ "item_id": @ "id",      @ " Item.name ": @" ItemName "   }]];
Set the underline to automatically turn the hump
{  "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
Optional attribute (meaning that this property can be null or empty)
{  "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
Ignore attributes (that is, ignore this property completely)
{  "id": "123",  "name": null} @interface Productmodel:jsonmodel@property (assign, nonatomic) int id; @property ( Strong, nonatomic) nsstring<ignore>* customproperty; @end @implementation Productmodel@end
Set all properties to be optional (all property values can be empty)
@implementation productmodel+ (BOOL) propertyisoptional: (nsstring*) propertyname{  return YES; @end
Using the HTTP request that comes with Jsonmodel
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 ...                               }];
Convert model to Dictionary or JSON-formatted string
productmodel* pm = [[ProductModel alloc] initwithstring:jsonstring error:nil];p m.name = @ "Changed name";//convert to Dict ionarynsdictionary* Dict = [pm Todictionary];//convert to textnsstring* string = [pm toJSONString];
Conversion of custom data
@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
Custom handling of specified properties
@interface Productmodel:jsonmodel@property (assign, nonatomic) int id; @property (strong, nonatomic) nsstring* name; @pro Perty (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
Custom JSON Checksum
@interface Productmodel:jsonmodel@property (assign, nonatomic) int id; @property (strong, nonatomic) nsstring* name; @pro Perty (assign, nonatomic) float price; @property (Strong, nonatomic) Nslocale *locale; @property (Strong, nonatomic) Nsnumb Er <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

Use of Jsonmodel in IOS

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.