objective-c - SBJSON 编码包含另一个对象数组的对象

标签 objective-c ios json sbjson

我有一个 json 编码问题:

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

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;

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

最佳答案

您不应将 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];

关于objective-c - SBJSON 编码包含另一个对象数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604502/

相关文章:

ios - 检测对象的至少一个属性是否被修改

ios - estimatedRowHeight 如何影响性能?

ios - 动态创建一个json对象

php - 从通过 AJAX 检索的对象设置文本字段值

ruby-on-rails - 在 rails api 中更新嵌套模型

ios - iOS6 的 UITableViewStylePlain 和 iOS 7 的 UITableViewStyleGrouped

iphone - iOS 子类 UICollectionViewCell 自定义初始化方法

ios - 在 SwiftUI 中启动屏幕图像拉伸(stretch)

ios - 捆绑的 Realm 数据库,但结果集为空

angularjs - 使用 Angularjs 将 Excel 转换为 JSON