受 RestKit 启发。一个非常好的 Objective-C 框架,它将 NSDictionary 或 NSArray 的 JSON 响应映射到 NSObject 子类以用于 iOS。
将 JTObjectMapping/ 中的所有文件复制到您的项目中。
假设这是一个在解析后表示为 NSDictionary 的 JSON User 对象响应
{ "create_date" = "1970-01-01T00:00:00+0000"; "p_age" = 30; "p_childs" = ( Mary, James ); "p_name" = Bob; "p_title" = Manager; "social_networks" = { "twitter" = "@mystcolor"; "facebook" = "yourFacebookID"; } }
准备好您的 JSON,使用 [NSObject objectFromJSONObject:json mapping:mapping] 来转换。
...
NSDictionary *json = <Parsed JSON response from above>;
//
// Use +[NSObject objectFromJSONObject:mapping:] to convert
// the NSDictionary into your JTUserTest object
//
JTUserTest *user = [JTUserTest objectFromJSONObject:json mapping:mapping];
...
定义必要的映射,从字典键到属性 keyPath。
// Define the mapping of a nested custom object - JTSocialNetworkTest
NSDictionary *socialNetworkMapping = [NSDictionary dictionaryWithObjectsAndKeys:
@"twitterID", @"twitter",
@"facebookID", @"facebook",
nil];
NSDictionary *mapping = [NSDictionary dictionaryWithObjectsAndKeys:
@"name", @"p_name",
@"title", @"p_title",
@"age", @"p_age",
@"childs", @"p_childs",
[NSDate mappingWithKey:@"createDate"
dateFormatString:@"yyyy-MM-dd'T'HH:mm:ssZ"], @"create_date",
[JTSocialNetworkTest mappingWithKey:@"socialNetwork"
mapping:socialNetworkMapping], @"social_networks",
nil];
当然,您需要定义自己的 User 对象,并带有相应的 @synthesize 属性,这样就全部完成了。
// JTSocialNetworkTest.h
@interface JTSocialNetworkTest
@property (nonatomic, copy) NSString *twitter;
@property (nonatomic, copy) NSString *facebook;
@end
// JTSocialNetworkTest.m
@implementation
@end
// JTUserTest.h
@interface JTUserTest : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSNumber *age;
@property (nonatomic, strong) NSDate *createDate;
@property (nonatomic, strong) NSArray *childs;
@property (nonatomic, strong) JTSocialNetworkTest *socialNetwork;
@end
// JTUserTest.m
#import "JTUserTest.h"
@implementation JTUserTest
@end
有关更详细的使用说明,请参阅 JTObjectMappingTests.m,将在不久的将来添加更详细的说明。
v1.1.2
v1.1.1
v1.1
v1.0.7
v1.0.6
#define JTOBJECTMAPPING_DISABLE_KEYPATH_SUPPORT = 1
来禁用它。v1.0.5
v1.0.4
v1.0.3
v1.0.2
v1.0.1