BWJSONMatcher 1.1.3

BWJSONMatcher 1.1.3

测试已测试
语言 Obj-CObjective C
许可证 MIT
发布时间最后发布时间2016年8月

BurrowsWang 维护。



  • 作者:
  • BurrowsWang

BWJSONMatcher 是一个轻量级的 Objective-c 库,可以帮助您轻松地将 JSON 数据或 JSON 字符串或 JSON 对象与数据模型匹配。

它提供以下功能:

  • 通用的 JSON 匹配器,可以将 JSON 数据或 JSON 字符串或 JSON 对象与数据模型匹配
  • 基于 NSObjectcatalog,帮助您轻松地将 JSON 与任何对象转换
  • 三种 协议,您的数据模型应遵守

如何使用

API 文档可在 CocoaDocs - BWJSONMatcher 找到。

可以在此找到 示例项目,具体请参考 此处

如何使用 NSObject+BWJSONMatcher(推荐)

#import "NSObject+BWJSONMatcher.h"

...
// convert json data to data model
NSData *jsonData = your-json-bytes;
YourValueObject *dataModel = [YourValueObject fromJSONData:jsonData];

// convert json string to data model
NSString *jsonString = @"{your-json-string}";
YourValueObject *dataModel = [YourValueObject fromJSONString:jsonString];

// convert json object to data model
NSDictionary *jsonObject = @{your-json-object};
YourValueObject *dataModel = [YourValueObject fromJSONObject:jsonObject];

...
YourValueObject *dataModel = instance-of-your-value-object;

// convert data model to json data
NSData *jsonData = [dataModel toJSONData];
// convert data model to json string
NSString *jsonString = [dataModel toJSONString];
// convert data model to json object
NSDictionary *jsonObject = [dataModel toJSONObject];
...

如何使用 BWJSONMatcher

#import "BWJSONMatcher.h"

...
NSDictionary *jsonObject = @{your-json-object};
YourValueObject *dataModel = [BWJSONMatcher matchJSON:jsonObject withClass:[YourValueObject class]];

...
NSString *jsonString = "[{your-json-string}, ...]";
NSArray *jsonArray = [BWJSONMatcher matchJSONString:jsonObject withClass:[YourValueObject class]];

...
YourValueObject *dataModel = instance-of-your-value-object;
NSDictionary *jsonObject = [BWJSONMatcher convertObjectToJSON:dataModel];
...

如何处理类型为 NSArray 的属性

如在以下示例中 这里,如果您有一个类型为 NSArray 的属性,使您的 ValueObject 符合协议 BWJSONHasArrayProperties 并实现方法 typeInProperty:,告诉 BWJSONMatcher 此数组中包含的对象类型。

- (Class)typeInProperty:(NSString *)property {
    if ([property isEqualToString:@"emails"]) {
        return [NSString class];
    }

    return nil;
}

如何忽略某些属性

在某些情况下,可能有一些属性不需要从 JSON 数据中提取。使您的 ValueObject 符合协议 BWJSONHasIgnoredProperties 并在类方法 ignoredProperties: 中提供要忽略的属性名称,BWJSONMatcher 在匹配 JSON 数据与数据模型时将忽略这些属性。

+ (NSArray *)ignoredProperties {
    return @[@"street", @"valet"];
}

如何重命名属性

在使用某些公开API时,返回的JSON中通常会出现考虑不周祥的属性名称或与您的约定不一致的名称。在这种情况下,只需确保您的数据模型符合协议BWJSONHasToMapProperty,提供一个属性mapper,将数据模型中的名称转换为JSON中的名称。示例代码

+ (NSDictionary *)propertyMapper {
    return @{@"userId": @"id", @"userName": @"user_name"};
}

安装

其他方法

  • 将所有文件复制到您的项目中
  • 将项目作为动态框架导入,注意:请将框架添加到Embedded Binaries
  • 将项目作为静态库导入,注意:请在构建设置中添加-ObjCOther Linker Flags

许可证

所有源代码均按照MIT许可证进行许可。