序列化(将对象转换为JSON数据)
- 创建需要序列化的对象:通常是一个符合JSON结构的
NSDictionary
或NSArray
。
- 使用
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数据转换为对象)
- 获取JSON数据:一般为
NSData
类型,可以从网络请求、文件读取等方式获取。
- 使用
NSJSONSerialization
进行反序列化:调用JSONObjectWithData:options:error:
方法将NSData
转换为NSDictionary
或NSArray
对象。
核心代码如下:
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);
}