首页 > 解决方案 > 如何使用 Struct Encodable、iOS、Swift 在 Alamofire 中发布没有键的对象数组

问题描述

我想通过发布以下正文Alamofire。这是确切的帖子正文。我已经用邮递员测试过了

[
   {
      "keyone":{
         "name":"abc",
         "value":"1"
      },
      "keytwo":{
         "age":"23",
         "id":"9812fvereaere112"
      },
      "keythree":{
         "expired":true,
         "freshuser":false
      },
      "keyfour":{
         "license":true
      }
   }
]

Struct为此创建了一个。

// MARK: - Keyfour
struct Keyfour: Codable {
    let license: Bool
}

// MARK: - Keyone
struct Keyone: Codable {
    let name, value: String
}

// MARK: - Keythree
struct Keythree: Codable {
    let expired, freshuser: Bool
}

// MARK: - Keytwo
struct Keytwo: Codable {
    let age, id: String
}

然后我从这些对象创建了一个数组,并尝试将其用作 Alamofire.but 的参数,Alamofire[String: Any]我应该发送 [Dictionary<String, Any>]. 我怎样才能做到这一点。

我试图将我的对象数组转换为字典,但使用以下方法失败

 private func convertdocprocesstoDictonary(jsonstring: String) -> Dictionary<String, Any>? {
        if let data = jsonstring.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any>
            } catch let jsonerr {
                print("\(jsonerr.localizedDescription)")
            }
        }
        return nil
    }

// Tried this with [Dictionary<String, Any>] as well.it fails too


let jdat = try JSONEncoder().encode(Array_of_Objects)
let jstring = String(data: jdat, encoding: .utf8)
let dic = convertdocprocesstoDictonary(jsonstring: jstring) 

然后附加 dic 作为参数。什么都没有成功。希望您对此有所帮助。祝你有美好的一天,并保持安全。

标签: iosswiftdictionaryhttp-postalamofire

解决方案


推荐阅读