Swift-Alamofire请求失败,因为json和字典中的参数格式错误

时间:2019-06-26 06:27:23

标签: json swift dictionary alamofire objectmapper

我有一个模型类,名称为UserList,它具有ID,代码和[Friends]作为数组。在这种情况下,Friends也是一个模型类。朋友班的属性是姓名,姓氏,电子邮件,公司,电话。

class Friends: NSObject,Codable,Mappable {

    var phone = String()
    var name = String()
    var surname = String()
    var company = String()
    var email = String()

    required init?(map: Map){

    }
    override init() {

    }

    func mapping(map: Map) {
     name <- map["name"]
     email <- map["email"]
     company <- map["company"]
     surname <- map["surname"]
     phone <- map["phone"]
    }
}

class UserList: NSObject,Codable,Mappable {

    var friendsList = [Friends]()
    var code = Int()
    var id = String()

    required init?(map: Map){

    }
    override init() {

    }

    func mapping(map: Map) {
      id <- map["id"]
      code <- map["code"]
      friendsList <- map["friendsList"]
    }
}

我这样获取UserList类:

let contacts = UserList()

orderedContacts.forEach({
    for record in $0.value {
        let contact = Friends()
         contact.name = record.givenName
         contact.surname = record.familyName
         contact.email = (record.emailAddresses.first?.value as String?) ?? ""
         contact.company = record.organizationName
         contact.phone = (record.phoneNumbers.first?.value.stringValue) ?? ""
         contacts.friendsList.append(contact)
    }
})

contacts.id = "57459bd9-f4c6-4fca-b5a4-6b4bc603b64c"
contacts.code = "BFF"

毕竟,我有一个JSON字符串,并使用SwiftyJSON对其进行了转换。 此转换为我提供了正确的json字符串。没有问题。之后,我应该将此json字符串转换为Dictionary作为Dictionary,以将其作为参数传递给Alamofire请求。

let newJsonA  = contacts.toJSONString(prettyPrint: true)!
let newJson :Dictionary<String,Any>? = convertToDictionary(text: newJsonA) 

当我发送字符串进行转换时,我在控制台上看到它的打印内容:

["Friends": <__NSArrayI 0x12aa96e00>(
{
    name = "First";
    email = "";
    company = "";
    surname = "Record";
    phone = "123456789";
},
{
    name = "Second";
    email = "";
    company = "";
    surname = "Record";
    phone = "987654321";
}
)
"code": "BFF", 
"id": "57459bd9-f4c6-4fca-b5a4-6b4bc603b64c" ]

如您所见,json的格式不正确。字典转换后,“ <__ NSArrayI 0x12aa96e00>(”已添加到字典中。这导致Alamofire请求失败。

Error Domain=com.alamofireobjectmapper.error Code=2 "ObjectMapper failed to serialize response." UserInfo={NSLocalizedFailureReason=ObjectMapper failed to serialize response.}

我确定我正确映射了响应值。我认为问题是我作为参数发送的json字典数组。有没有人遇到过这个问题?

0 个答案:

没有答案