将对象序列化为JSON

时间:2013-01-14 19:46:50

标签: 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数组添加到词典之前对其执行某些操作?

2 个答案:

答案 0 :(得分:3)

试试这个:

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

假设self.orderedIngredients是一个包含ingredients个对象的数组,ingredients中有一个名为name的属性,

[self.orderedIngredients valueForKey:@"name"]

将返回所有名称的数组。

答案 1 :(得分:1)

如果您的components数组列表包含自定义类对象,则应为该类创建一个序列化程序。