- 实现步骤:
- 创建模型类:定义一个继承自
MTLModel
的Objective-C类,用于表示JSON数据结构。
- 定义属性:在模型类中定义与JSON数据结构中字段对应的属性,即
name
和age
。
- 实现JSON属性映射:通过实现
+ (NSDictionary *)JSONKeyPathsByPropertyKey
方法,指定JSON中的键与模型属性的映射关系。
- 解析JSON数据:使用
MTLJSONAdapter
类将JSON数据转换为模型对象。
- 关键代码示例:
#import <Mantle/Mantle.h>
@interface Person : MTLModel <MTLJSONSerializing>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation Person
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"name": @"name",
@"age": @"age"
};
}
@end
- **JSON数据解析**:
NSDictionary *jsonDict = @{@"name": @"John", @"age": @25};
NSError *error;
Person *person = [MTLJSONAdapter modelOfClass:Person.class fromJSONDictionary:jsonDict error:&error];
if (error) {
NSLog(@"解析错误: %@", error);
} else {
NSLog(@"姓名: %@, 年龄: %ld", person.name, (long)person.age);
}