我有一个 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/