Search code examples
iosswiftapialamofire

Error to parse from alomofire post request


I have an issue with parsing using alamofire. I get an error to try to decode the json file that i get in return from the request. I have tried to parse JSON file that looks like this:

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

})

It Gives me an error that looks like this:

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

The user model looks like this:

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"
    }
 }

And the function looks like this:

    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")
                    }
}

How do i fix the issue?


Solution

  • You are ignoring the root object, the dictionary with key data.

    Create another struct

    struct Root : Decodable {
        let data : UserModel
    }
    

    And please name structs with starting capital letter and you don't need the CodingKeys if the struct member names match the keys

    struct UserModel: Codable {
        let id: String
        let nickname: String
        let options: Options
        let rooms: String
    
    
    struct Options: Codable {
        var avatar: String?
     }
    

    Then decode

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

    Consider that AF can decode JSON with JSONDecoder implicitly.