iOS platform KVC-based JSON and data object binding

Source: Internet
Author: User

iOS platform based on KVC JSON and data object binding Chszs, not allowed to reprint without the Bo master. Permission to reprint should be marked by the author and blog home: Http://blog.csdn.net/chszs

It's not difficult to manipulate JSON data on the iOS platform, but we have a simpler solution that uses KVC, the full name is Key-value Coding.

Suppose the developer (you) developed an application whose data comes from external to the Web service, retrieving some JSON data from the Web service, with the following data:

{"count": 3, "sum": 9.0, "average": 3.0}

To get data from the server, you need to call Nsjsonserializationalization's Jsonobjectwithdata method and retrieve the data from the serialized dictionary, such as:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];NSLog(@"%d", [[dictionary objectForKey:@"count"] intValue]); // prints 3RdNSLog(@"%.1f", [[dictionary objectForKey:@"sum"] doubleValue]); // prints 9.0NSLog(@"%.1f", [[dictionary objectForKey:@"average"] doubleValue]); // prints 3.0

However, the above values are more fragmented, and it may be easier to interact directly with strongly typed data objects when doing application development. For example, you might want to create a statistics statistic class that represents the type of data returned through a Web service, as follows:

@interface Statistics : NSObject@property (nonatomic) int count;@property (nonatomic) double sum;@property (nonatomic) double average;@end

You can then extract the values from the dictionary to populate the above objects:

Statistics *statistics = [[Statistics alloc] init];statistics.count = [[dictionary objectForKey:@"count"] intValue];statistics.sum = [[dictionary objectForKey:@"sum"] doubleValue];statistics.average = [[dictionary objectForKey:@"average"] doubleValue];

To make things easier and avoid code duplication, you can put this code in the initialization of the statistics class:

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {    self = [super init];    if (self) {        self.count = [[dictionary objectForKey:@"count"] intValue];        self.sum = [[dictionary objectForKey:@"sum"] doubleValue];        self.average = [[dictionary objectForKey:@"average"] doubleValue];    }    return self;}

The code-binding JSON responds to the statistics instance as follows:

Statistics *statistics = [[Statistics alloc] initWithDictionary:dictionary];

In any case, you can use the properties of this strongly typed data object to access the data returned from the server:

NSLog(@"%d", statistics.count); // prints 3NSLog(@"%.1f", statistics.sum); // prints 9.0NSLog(@"%.1f", statistics.average); // prints 3.0

The code above works fine, and mapping JSON data to strongly typed data objects is a very good approach.

However, there is a simpler solution: KVC. NSObject Setvaluesforkeyswithdictionary: Method can be used to automatically map all values on a given dictionary to the properties of an object. Using this method, Initwithdictionary: The method is simplified as follows:

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {    self = [super init];    if (self) {        [self setValuesForKeysWithDictionary:dictionary];    }    return self;}

There is no need to manually map a dictionary into an item-to-attribute value, declaring the property with the appropriate name and type is sufficient, and the following code works well in Swift:

class Statistics: NSObject {    var count: Int = 0    var sum: Double = 0    var average: Double = 0    init(dictionary: [String:AnyObject]) {        super.init()        setValuesForKeysWithDictionary(dictionary);    }}

In addition, if you need to customize the assignment of property names or property values, you can simply override the Setvalue:forkey: method. For example, suppose the server refers to an average attribute with a different name:

{"count": 3, "sum": 9.0, "mean": 3.0}

You can override the Setvalue:forkey: method to ensure that the values are correctly mapped to the attribute:

- (void)setValue:(id)value forKey:(NSString *)key {    if ([key isEqual:@"mean"]) {        key = @"average";    }    [super setValue:value forKey:key];}

Finally, you can use KVC to ignore the values you don't want. For example, suppose the server's response also contains a property named "median":

{"count": 3, "sum": 9.0, "average": 3.0, "median": 3.0}

Because the statistics class does not have a "Median" attribute defined, the Setvaluesforkeyswithdictionary: Method throws a Nsunknownkeyexception exception. To avoid throwing this exception, you can simply rewrite the Setvalue:forundefinedkey:: Method.

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {    // No-op}

Copyright NOTICE: This article for Bo Master Chszs original article, without Bo Master permission not reproduced.

iOS platform KVC-based JSON and data object binding

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.