MST

星途 面试题库

面试题:Objective-C 中 JSON 数据序列化与反序列化常用方法

在 Objective-C 进行《Objective-C高性能网络编程中的数据序列化与反序列化》时,使用系统自带框架实现 JSON 数据的序列化与反序列化,分别写出关键步骤和核心代码。
26.3万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

序列化(将对象转换为JSON数据)

  1. 创建需要序列化的对象:通常是一个符合JSON结构的NSDictionaryNSArray
  2. 使用NSJSONSerialization进行序列化:调用dataWithJSONObject:options:error:方法将对象转换为NSData类型的数据。 核心代码如下:
NSDictionary *jsonDict = @{@"key": @"value"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
    NSLog(@"序列化错误: %@", error);
} else {
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"序列化后的JSON字符串: %@", jsonString);
}

反序列化(将JSON数据转换为对象)

  1. 获取JSON数据:一般为NSData类型,可以从网络请求、文件读取等方式获取。
  2. 使用NSJSONSerialization进行反序列化:调用JSONObjectWithData:options:error:方法将NSData转换为NSDictionaryNSArray对象。 核心代码如下:
NSString *jsonString = @"{\"key\":\"value\"}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (!jsonObject) {
    NSLog(@"反序列化错误: %@", error);
} else {
    NSLog(@"反序列化后的对象: %@", jsonObject);
}