面试题答案
一键面试使用MJExtension进行JSON解析与模型转换步骤
- 添加MJExtension框架:
- 如果使用CocoaPods,在
Podfile
文件中添加pod 'MJExtension'
,然后执行pod install
。 - 手动导入则将MJExtension文件夹拖入项目,并添加必要的依赖库。
- 如果使用CocoaPods,在
- 定义自定义模型类: 假设我们有一个包含姓名和年龄的JSON对象,定义模型类如下:
#import <Foundation/Foundation.h>
#import "MJExtension.h"
@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation Person
@end
- JSON数据:
{
"name":"张三",
"age":25
}
- 解析与模型转换:
#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *jsonString = @"{\"name\":\"张三\",\"age\":25}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (!error) {
Person *person = [Person mj_objectWithKeyValues:jsonDict];
NSLog(@"姓名:%@,年龄:%ld", person.name, (long)person.age);
}
}
@end
上述代码首先将JSON字符串转换为NSData
,再解析为NSDictionary
,最后使用MJExtension的mj_objectWithKeyValues:
方法将字典转换为自定义模型Person
的实例。