在Objective C中,可以使用NSJSONSerialization类来实现JSON序列化和反序列化。具体实现如下:
- 将数据序列化为JSON格式:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:yourData options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(@"Error serializing data to JSON: %@", error.localizedDescription);
} else {
//use jsonData to send to server
}
上述代码会将你的数据(yourData)序列化为JSON格式,存储在NSData对象中。如果发生错误,会打印错误信息。
- 将JSON数据反序列化为Objective C对象:
NSError *error;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
if (!jsonObject) {
NSLog(@"Error deserializing JSON data: %@", error.localizedDescription);
} else {
//use jsonObject as your Objective C object
}
上述代码会将JSON数据(存储在NSData对象中)反序列化为Objective C对象。如果发生错误,会打印错误信息。
以上就是在Objective C中实现JSON序列化和反序列化的简单示例。