在Objective-C中将自定义类转换为JSON数组或JSON字典,可以通过以下步骤实现:
initWithCoder:
和encodeWithCoder:
方法。这样可以实现自定义类的序列化和反序列化。@interface CustomClass : NSObject <NSCoding>
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
@end
@implementation CustomClass
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
@end
dataWithJSONObject:options:error:
方法将自定义类转换为JSON数据。CustomClass *customObject = [[CustomClass alloc] init];
customObject.name = @"John";
customObject.age = 25;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:[customObject dictionaryRepresentation] options:NSJSONWritingPrettyPrinted error:&error];
if (!jsonData) {
NSLog(@"转换为JSON数据时出错:%@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"转换后的JSON数据:%@", jsonString);
}
JSONObjectWithData:options:error:
方法将JSON数据转换为NSDictionary或NSArray,然后根据自定义类的属性进行赋值。NSString *jsonString = @"{\"name\":\"John\",\"age\":25}";
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (!jsonDict) {
NSLog(@"转换为JSON字典时出错:%@", error);
} else {
CustomClass *customObject = [[CustomClass alloc] init];
customObject.name = jsonDict[@"name"];
customObject.age = [jsonDict[@"age"] integerValue];
NSLog(@"转换后的自定义类:%@", customObject);
}
通过以上步骤,你可以在Objective-C中将自定义类转换为JSON数组或JSON字典。请注意,这里的示例代码仅为演示目的,实际应用中可能需要根据自定义类的具体属性进行相应的转换和赋值操作。
领取专属 10元无门槛券
手把手带您无忧上云