BWJSONMatcher 是一个轻量级的 Objective-c 库,可以帮助您轻松地将 JSON 数据或 JSON 字符串或 JSON 对象与数据模型匹配。
它提供以下功能:
JSON 匹配器
,可以将 JSON 数据或 JSON 字符串或 JSON 对象与数据模型匹配NSObject
的 catalog
,帮助您轻松地将 JSON 与任何对象转换协议
,您的数据模型应遵守API 文档可在 CocoaDocs - 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];
...
#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 的属性,使您的 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
-ObjC
到Other Linker Flags
所有源代码均按照MIT许可证进行许可。