我正在使用AlamoFire进行失败的帖子调用,因为json缺少一个字段。问题似乎是因为我试图在json中发送一个可选变量发送到后端。
func toJSON() -> Dictionary<String, AnyObject> {
let subCategory = self.adCategory!.toJSON()
let images = self.adImages
var imgArray = [Dictionary<String, AnyObject>]()
for image in images! {
let img = image as! AdImage
imgArray.append(img.toJSON())
}
return [
"title": self.title as AnyObject,
"description": self.adDescription as AnyObject,
"category": subCategory as AnyObject,
"images": imgArray as AnyObject
]
}
标题,说明和图像工作正常。类别没有。
当我在调用Alamofire之前打印字典时,类别带有'='而不是':'以及';',如下所示:
"category": {
parent = {
slug = "weird-widgets";
};
slug = widgets;
这是来自SubCategory的代码toJSON():
func toJSON() -> Dictionary<String, Any> {
let category = self.category?.toJSON()
return [
"slug": self.slug as AnyObject,
"parent": category as AnyObject
]
}
是否有正确的方法来包装可选类型以避免此类问题?我尝试了几种方法,但没有一种方法有效。