尽管投票最高的答案对字典数组或其他可序列化对象有效,但对自定义对象无效。
事情就是这样,您需要遍历数组并获取每个对象的字典表示并将其添加到要序列化的新数组中。
NSString *offersJSONString = @"";
if(offers)
{
NSMutableArray *offersJSONArray = [NSMutableArray array];
for (Offer *offer in offers)
{
[offersJSONArray addObject:[offer dictionaryRepresentation]];
}
NSData *offersJSONData = [NSJSONSerialization dataWithJSONObject:offersJSONArray options:NSJSONWritingPrettyPrinted error:&error];
offersJSONString = [[NSString alloc] initWithData:offersJSONData encoding:NSUTF8StringEncoding] ;
}
至于 Offer 类中的 dictionaryRepresentation 方法:
- (NSDictionary *)dictionaryRepresentation
{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
[mutableDict setValue:self.title forKey:@"title"];
return [NSDictionary dictionaryWithDictionary:mutableDict];
}