Get along with Json and Model.

Source: Internet
Author: User
Tags time zones

Get along with Json and Model.

The JsonData returned by the server in iOS can be easily parsed using the built-in json parsing class or any JsonKit or SBJson framework, if you don't feel any trouble, you can use the KVC value here ~ Hard encoding of such a string...

Therefore, it is necessary to convert to a Model object ~ Json objects can be mapped to model objects ~ Such as JSONModel and Mantle ~ The most important thing to mention is the MJExtension ~ Very good, especially in terms of Conversion Efficiency ~ I dare not say that this is better than MJExtension. I can only say that it is more in line with my own simple, crude, and effective development and use habits ~

After testing, I used my Macbook to map the array consisting of the 1000 identical test dictionaries provided in the following article. MJExtension took only 0.07 seconds, the tool I wrote took about 0.25 seconds... the time consumed is 3 ~ 4 times the interval ~ Because the model name and class name are identified and integrated with string processing for ing, it is natural to consume more time ~ The processing through GCD's concurrent operations has not significantly improved the efficiency ~

The conclusion obtained after consideration is that the internal structure of each model needs to be fully scanned during transformation. The conversion of a single model is natural, but the overall ing of the array is, because the models stored in the array are the same, it is unnecessary to scan an array with a length of 1000 for 999 times ~ The increase in the linear time consumption at reduces the overall efficiency ~ This is the first version. After all, even if the cache class structure is not used to improve efficiency, the ing speed of the 1000 models for 0.25 seconds is still acceptable ~

Next, let's talk about what this is.

First look at a set of false data for testing.


-(NSDictionary *)fakeData{    return@{@"name":@"jack",@"id":@"123",@"code":@"4567890-",@"other":@{@"attr1":@"value1",@"attr2":@"150",@"attr3":@"0.8"},@"test":@"3",@"d":@"4.5",@"l":@3456789,@"f":@"123.123",@"b":@"1",@"date1":@"13567890456",@"date2":@"2015-4-3 11:18:24",@"arr":@[    @{@"attr1":@"value1",@"attr2":@"150",@"attr3":@"0.8"},    @{@"attr1":@"value1",@"attr2":@"150",@"attr3":@"0.8"}],@"path":@{    @"third":@{@"name":@"rose",@"age":@"123"},    @"3rd":@{@"name":@"rose",@"age":@"123"},    @"sub":@{        @"fourth":@{@"name":@"rose",@"age":@"123"},        @"4th":@{@"name":@"rose",@"age":@"123"}}}};}



The data volume is not large. We can see that the data on the outermost layer contains strings, dates, numbers, arrays, and dictionaries ~ KEY: @ 3456789 corresponding to 'L' maps to long type data, and 'F' maps to float type data, although the target is a number type, however, it does not matter what format is in json ~

In terms of date, we can see that date1 uses the timestamp, while date2 uses the date string ~ All processing of date data is done through NESDateHandler. Frankly speaking, this thing can already be split into an independent date tool ~ When I wrote this thing, I still had some snacks, but this is not the focus of today ~ The test cases that have been pasted with this class almost all of its usage ~ Complete Test Cases and source code can be downloaded at the end.


-(Void) testBlockHandler {NSDateFormatter * fmt = [[NSDateFormatter alloc] init]; fmt. dateFormat = @ "yyyy-MM-dd"; NSDate * date1 = [NESDateHandler dateWith: @ "date: 2015-10-10" using: ^ NSDate * (id object) {NSString * dateString = [[object componentsSeparatedByString: @ ":"] lastObject]; return [fmt dateFromString: dateString] ;}]; NSDate * date2 = [fmt dateFromString: @ "2015-10-10"]; XCTAssertEqualObjects (date1, date2);}-(void) testCustomFormatter {NSDateFormatter * fmt = [[NSDateFormatter alloc] init]; fmt. dateFormat = @ "yyyy-MM-dd"; [NESDateHandler setDateFormatter: fmt]; NSDate * date1 = [NESDateHandler dateWith: @ "11:11:11"]; NSDate * date2 = [NESDateHandler dateWith: @ "2015"]; // The date string does not match and is processed according to the timestamp. The results of the two should be the same. XCTAssertEqualObjects (date1, date2 ); date1 = [NESDateHandler dateWith: @ "2015-10-10"]; date2 = [fmt dateFromString: @ "2015-10-10"]; XCTAssertEqualObjects (date1, date2); [NESDateHandler setDateFormatter: [NESDateHandler defaultDateFormatter];}-(void) testdefadatedatestringhandler {NSDate * date = [NSDate dateWithTimeIntervalSince1970: 60*60*24*365*45 + 60*60*24*11]; // 45 years + 11 leap years + 8 time zones NSString * str = @ "08:00:00"; NSString * target = [NESDateHandler stringWith: date]; XCTAssertEqualObjects (str, target);}-(void) testCustomDateStringHandler {NSString * str = @ "Custom date Processor"; [NESDateHandler setDateStringHandler: ^ NSString * (NSDate * date) {return @ "Custom date Processor" ;}]; NSString * target = [NESDateHandler stringWith: [NSDate date]; XCTAssertEqualObjects (str, target); [NESDateHandler setDateStringHandler: [NESDateHandler defaultDateStringHandler];}-(void) testCustomDateHandler {[NESDateHandler setDateHandler: ^ NSDate * (id object) {return [NSDate dateWithTimeIntervalSince1970: 60*60*24*365*100];}]; NSDate * date = [NSDate dateWithTimeIntervalSince1970: 60*60*24*365*100]; NSDate * target = [NESDateHandler dateWith: @ "2015"]; Centers (target); XCTAssertEqualObjects (date, target); [NESDateHandler setDateHandler: [NESDateHandler defaultDateHandler];} -(void) testDateFromInvalidateString {NSDate * date = [NESDateHandler dateWith: @ "updated"]; NSDate * dateNow = [NSDate date]; XCTAssertNotNil (date); NSTimeInterval t = dateNow. timeIntervalSince1970-date. timeIntervalSince1970; XCTAssert (t> 0 & t <0.001);}-(void) testDateFromTimeInterval {NSDate * date1 = [NESDateHandler dateWith: @ "22:11:11. 123 "]; NSDate * date2 = [NESDateHandler dateWith: @" 2015 "]; XCTAssertNotNil (date1); week (date2); XCTAssertEqualObjects (date1, date2);}-(void) testDateFromValidateString {NSDate * date1 = [NESDateHandler dateWith: @ "2014-4-5 4-5 22:10:19"]; XCTAssertNotNil (date1 );}

The processing of date strings is not available in MJExtension. It is also something I need ~ The next step is how to define the model for the above false data.

#import <Foundation/Foundation.h>#import "NESOtherModel.h"#import "NESThirdModel.h"#import "NESFourthModel.h"@interface NESDemoModel : NSObject@property (nonatomic,retain) NSString *name;@property (nonatomic,retain) NSString *test_id;@property (nonatomic,retain) NSString *code;@property (nonatomic,retain) NESOtherModel *other;@property (nonatomic,assign) int test;@property (nonatomic,assign) double d;@property (nonatomic,assign) long l;@property (nonatomic,assign) float f;@property (nonatomic,assign) BOOL b;@property (nonatomic,retain) NSDate *date1;@property (nonatomic,retain) NSDate *date2;@property (nonatomic,retain) NSArray *other_arr;@property (nonatomic,retain) NESThirdModel *_path_third;@property (nonatomic,retain) NESThirdModel *_path_3rd;@property (nonatomic,retain) NESFourthModel *_path_sub_fourth;@property (nonatomic,retain) NESFourthModel *_path_sub_4th;@property (nonatomic,assign) NSString * notExists_;@end

There is no protocol, and no additional header files need to be introduced during definition, just inherit from NSObject directly ~ The naming rules for attributes are as follows:

1. Direct ing. The property name is the same as the json key value.
2. Indirect ing. It starts with a letter and connects with '_'. The front side is an arbitrary string and the back side is a json key,
Example:@ Property (nonatomic, retain) NSString * test_id;Corresponding to the id in json
3. array ing. For array type attributes, use '_' to connect the model name and json key to complete the ing.
Example:@ Property (nonatomic, retain) NSArray * other_arr;Corresponding to the arr in json. The description of the model used for encapsulation is as follows:
4. Path ing. this parameter is used when you want to directly map an object in json to a model attribute. It starts with '_' and each level of path is connected '_'.
End with a json key. Path ing can contain multi-level paths.
Example:@ Property (nonatomic, retain) NESFourthModel * _ path_sub_fourth;Here is the second-level path ing, which is easy to understand against the data source above
5. ignore attributes. When you need to define an attribute not in a json object in the model and ignore the attribute during json String Conversion, add '_' At the end of the attribute name '_'
Example:@ Property (nonatomic, assign) NSString * notExists _;This is the field that does not perform any operations during ing.

For array ing in json objects, a class called NESModelFormat is used, which defines the global prefix and suffix. The default values are null strings and "Model ", from the definition of the file, we can see that'NESOtherModel'Class ~ Here, 'nes 'is the prefix. You need to configure both hands in the NESModelFormat alignment. Of course, the configuration is global. You only need to configure it once at the appropriate position ~ In this case, the effect of 'other _ arr' is to map the array corresponding to arr in json to an array composed of objects in the NESOtherModel class ~ What prefix and suffix are used in actual use ~

After the ing is completed, the reverse json string generated by the object is

{"B": "1", "test": "3", "f": "123.123", "name": "jack", "id ": "123", "code": "4567890-", "other": {"attr3": "0.8", "attr1": "value1", "attr2 ": "150"}, "d": "4.5", "l": "3456789", "date1": "2399-12-14 02:27:36", "date2 ": "11:18:24", "arr": [{"attr3": "0.8", "attr1": "value1", "attr2": "150 "}, {"attr3": "0.8", "attr1": "value1", "attr2": "150"}], "path": {"third ": {"age": "123", "name": "rose"}, "3rd": {"age": "123", "name": "rose "}, "sub": {"fourth": {"age": "123", "name": "rose"}, "4th": {"age": "123 ", "name": "rose "}}}}

Considering the length, no format is added ~

When the model object is used for dictionary conversion, it is relatively lazy to write...

 [NSJSONSerialization JSONObjectWithData:[self.jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];

All functions are available here ~ All APIs are defined in"NSObject + NESModel. h"Medium ~ There are three methods.

+(id)mappingWithObject:(id)object;-(NSString *)jsonString;-(id)foundationModel;

It looks like this:

NESDemoModel *model = [NESDemoModel mappingWithObject:self.fakeData];NSArray *arr = [NESDemoModel mappingWithObject:@[self.fakeData,self.fakeData,self.fakeData,self.fakeData]];NSDictionary *dict = arr.foundationModel;

OK ~ This is basically the content ~ There are also poor considerations and inadequate functions ~ You are welcome to give your comments or contact me if you need to add any unfulfilled requirements ~ Those within the capability scope will be added as soon as possible ~
Of course, this is my personal favorite method. To sum up, we can correctly process attributes of the NSDate type without writing code in the implementation file. The attributes are clearly known ~ If you like this method, please use this tool ~
If you have higher requirements on running efficiency, we strongly recommend that you use MJExtension ~

The download path is attached:
Https://github.com/DominicNestor/NESModelExtDemo

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.