【问题标题】:SBJSON encode Object who contain an array of another ObjectSBJSON 编码包含另一个对象数组的对象
【发布时间】:2012-05-15 15:57:07
【问题描述】:

我有一点 json 编码问题:

在将对象格式 JSON 发送到 php 服务器之前,我需要使用 SBJSON 对其进行编码 目前此示例代码有效:

NSArray *arrayData = [NSArray arrayWithObjects:
                      user.id == nil ? [NSNumber numberWithInt:-1] : user.id,
                      ProfessionField.text, NameField.text, RPPSField.text, RPPSField.text,
                      NameField.text, SurnameField.text, StreetField.text,
                      TownField.text, CpField.text, MailField.text,
                      PhoneField.text, FaxField.text, MobileField.text,
                   //   [user.horaires JSONRepresentation],
                      nil];

NSArray *arrayKey = [NSArray arrayWithObjects:
                     @"id", @"spe", @"name", @"rpps", @"cip",
                     @"name", @"surname", @"rue",
                     @"ville", @"cp", @"mail", 
                     @"tel", @"fax", @"port", 
                    // @"horaires",
                     nil];

NSDictionary *dataBrut = [NSDictionary dictionaryWithObjects:arrayData forKeys:arrayKey];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:dataBrut forKey:@"data"];
NSString *jsonRequest = [jsonDict JSONRepresentation];

问题是当我需要发送“user.horaires”(这里是评论) 此对象的 JSON 表示中的应用程序崩溃。

此对象是以下类的数组:

@interface Horaire : NSObject
{ 
    BOOL morning;
}

@property (nonatomic, strong) NSNumber  *id;
@property (nonatomic, strong) NSString  *open;
@property (nonatomic, strong) NSString  *close;

有人知道如何成功编码吗?

【问题讨论】:

    标签: objective-c ios json sbjson


    【解决方案1】:

    您不应该将 JSON 表示作为 JSON 项包含在内。 JSON 不能很好地“转义”字符串数据,因此嵌入的 JSON(除非您单独“转义”它)会导致解析阻塞。

    相反,您应该将用于生成 JSON 表示的字典或数组(即“user.horaires”本身)放置在您显示正在生成和插入的表示的位置。然后整个结构将在一次操作中进行 JSON 编码。

    即:

    NSArray *arrayData = [NSArray arrayWithObjects:
                      user.id == nil ? [NSNumber numberWithInt:-1] : user.id,
                      ProfessionField.text, NameField.text, RPPSField.text, RPPSField.text,
                      NameField.text, SurnameField.text, StreetField.text,
                      TownField.text, CpField.text, MailField.text,
                      PhoneField.text, FaxField.text, MobileField.text,
                      user.horaires,
                      nil];
    

    【讨论】:

    • 我尝试过,但它回答:JSONRepresentation 失败。错误是:Horaire IDK 不支持 JSON 序列化为什么导致我的对象数组非常简单
    • 那么,该对象是数组或字典,还是其他实现它自己的 JSONRepresentation 方法的对象?
    • 哦,好吧,我在做梦:p 我已经实现了这个对象的 JSONRepresentation,现在它工作正常,ty
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2020-11-29
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多