iphone - 将对象序列化为JSON

标签 iphone ios objective-c json nsarray

我是JSON格式的新手,但它对于我的尝试来说似乎很理想。我需要自定义NSObject(食谱),并通过电子邮件中的URL字符串将其发送。然后,收件人将在我的应用程序中打开链接,然后将解析URL。

我现有的实现方式是根据食谱的详细信息手动生成一个字符串,然后在另一端对其进行解码。我希望使用更标准的东西,例如JSON。

到目前为止,我已经向Recipe类添加了以下方法:

- (NSData *)jsonRepresentation
{
    NSDictionary *dictionary = @{@"name":self.name,
                         @"instructions":self.instructions};
    NSError* error;
    return [NSJSONSerialization dataWithJSONObject:dictionary
                                           options:NSJSONWritingPrettyPrinted
                                             error:&error];
}

我可以使用以下命令成功记录此NSData对象:
 [[NSString alloc]initWithData:recipe.jsonRepresentation
                      encoding:NSUTF8StringEncoding];

但是,我还不能添加成分列表(NSArray)。我试图简单地使用这个:
NSDictionary *dictionary = @{ @"name" : self.name,
                      @"instructions" : self.instructions,
                       @"ingredients" : self.orderedIngredients };

但是在记录时,我收到此错误:
Invalid type in JSON write (Ingredient)

如您所知,我对此很陌生。

我是否打算在将ingredients数组添加到字典之前对其进行处理?

最佳答案

尝试这个:

NSDictionary *dictionary = @{ @"name" : self.name,
                      @"instructions" : self.instructions,
                       @"ingredients" : [self.orderedIngredients valueForKey:@"name"] };

假设self.orderedIngredients是其中包含ingredients对象的数组,并且ingredients具有一个名为name的属性,
[self.orderedIngredients valueForKey:@"name"]

将返回所有名称的数组。

关于iphone - 将对象序列化为JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14325503/

相关文章:

ios - 如何在 Storyboard 中指定 UIButton 的内容模式?

ios - UIImage 和 UIView 的交互式模糊,如 iOS 8 spotlight

ios - 作为自定义 TableView 单元格的 Xib 文件崩溃

iphone - 为什么在所有方法都是可选的情况下使用 Objective-C 协议(protocol)?

iphone - UITableView 内容的背景图片

ios - 无法快速停止 UIView 动画

ios - 可达性和reachabilityWithHostName

ios - UIImagePickerController 不旋转和平移/缩放

ios - UITableViewCell 中的 UITextField——当它出现在屏幕上时以编程方式使其成为 firstResponder?

iphone - 如何以编程方式在 iPhone 上创建消息聊天气泡(如 iPhone 消息)