CYJSONValidator 0.1

CYJSONValidator 0.1

测试已测试
语言语言 Obj-CObjective C
许可证 自定义
发布最后发布2015年5月

李富强维护。



  • 作者:
  • 李杰森

CYJSONValidator是iOS上对RPJSONValidator进行JSON数据解析的一个简单且安全的包装器。在实际使用中,它对JSON数据的处理非常详细。我们希望同时获得安全和灵活性。本项目可以实现这一点。更重要的是,它使用起来非常简单。

示例

NSDictionary *json = @{
                           @"tag1": @"star",
                           @"tag2": @"jason",
                           @"totalNum": @(1616),
                           @"start_index": @"60",
                           @"return_number": @(30),
                           @"data" : @[],
                           @"tags" : [NSNull null],
                           @"config" : @{
                                   @"max_num" : @(30000),
                                   @"tag" : [NSNull null]
                                   }
                           };

例如,我们想获取json中“config”字段的“max_num”值;

常规方法

NSDictionary *configDic1 = [json objectForKey:@"config"];
    if (configDic1 != nil && [configDic1 isKindOfClass:[NSDictionary class]]) {
        id number = [configDic1 objectForKey:@"max_num"];
        if ([number isKindOfClass:[NSNumber class]] || [number isKindOfClass:[NSString class]]) {
            NSInteger maxNum = [number integerValue];
            NSLog(@"maxNum 1: %@", @(maxNum));
        }
    }

CYJSONValidator方法

在Objective-C中,id不支持点符号。这使得我很不满意。因此,我将返回值更改为实际类型,以便优雅地支持链式语法

    NSInteger maxNum3 = [[json cy_dictionaryKey](@"config") cy_integerKey](@"max_num");
    NSLog(@"maxNum 3: %@", @(maxNum3));

或者就这么简单!

    NSInteger maxNum = [[json cy_dictionaryKey:@"config"] cy_integerKey:@"max_num"];
    NSLog(@"maxNum: %@", @(maxNum));

错误处理

    // Handle NSNull
    NSArray *tags = [json cy_arrayKey:@"tags"];
    NSLog(@"%@", tags);
    // Handle wrong type
    NSString *string = [[json cy_dictionaryKey:@"data"] cy_stringKey:@"1"];
    NSLog(@"%@", string);