从 alomofire post 请求解析时出错

Error to parse from alomofire post request

我在使用 alamofire 进行解析时遇到问题。我在尝试解码 json 文件时出错,我从请求中获得 return 。 我试图解析如下所示的 JSON 文件:

success({
data =     {
    id = "eb259a9e-1b71-4df3-9d2a-6aa797a147f6";
    nickname = joeDoe;
    options =         {
        avatar = avatar1;
    };
    rooms = "<null>";
};

})

它给我一个看起来像这样的错误:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))

用户模型如下所示:

import Foundation

struct userModel: Codable {
    let id: String
    let nickname: String
    let options: options
    let rooms: String

enum CodingKeys: String, CodingKey {
    case id = "id"
    case nickname = "nickname"
    case options = "options"
    case rooms = "rooms"
    }
}

struct options: Codable {
   var avatar: String?
enum CodingKeys: String, CodingKey {
    case avatar = "avatar"
    }
 }

函数如下所示:

    func postUser(){
    AF.request("http://test.com/", method: .post, parameters: user).responseJSON {response  in
        guard let itemsData = response.data else {
            print("test1")
                      return
                    }
                    do {
                        print("hallo!")
                        let decoder = JSONDecoder()
                        print("")
                        print(itemsData)
                        print("")
                        print(response.description)
                        let items = try decoder.decode(userModel.self, from: itemsData)
                        print(items)
                        DispatchQueue.main.async {
                            print("test2")
                        }
                    } catch {
                        print(error)
                    print("test3")
                    }
}

我该如何解决这个问题?

您忽略了根对象,即键为 data 的字典。

创建另一个结构

struct Root : Decodable {
    let data : UserModel
}

并且请以首字母大写命名结构,如果结构成员名称与键匹配,则不需要 CodingKeys

struct UserModel: Codable {
    let id: String
    let nickname: String
    let options: Options
    let rooms: String


struct Options: Codable {
    var avatar: String?
 }

然后解码

 let result = try decoder.decode(Root.self, from: itemsData)
 let items = result.data

考虑到 AF 可以用 JSONDecoder 隐式解码 JSON。