Search code examples
jsonswiftapirequestjson-serialization

How to convert an object to a serializable JSON in swift


I'm the type to scour the web when I block but now I can't find or understand.

I have to do a simple post to an API, but I can't pass my object in parameters of my request.

When I test my var parameters with let checker = JSONSerialization.isValidJSONObject(parameters) the test is still false.

I must pass this variable "parameters" as the httpBody of my request guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}

    
    let userId: String
    let listItems: [ListItem]
    
    internal init(userId: String, listItems: [ListItem] = []) {
        self.userId = userId
        self.listItems = listItems
    }
    
    enum CodingKeys: String, CodingKey {
        case userId
        case listItems
    }
}

// MARK: - ListItem
struct ListItem: Codable {
    internal init(nameDrug: String, code_cip: String, unitStock: Double) {
        self.nameItem = nameItem
        self.code_cip = code_cip
        self.unitStock = unitStock
    }
    
    let nameItem, code_cip: String
    let unitStock: Double

    enum CodingKeys: String, CodingKey {
        case nameItem
        case code_cip
        case unitStock
    }
    
}```


The API expects a body under this structure

```    {
        "userId":"60c0ede9dfc16e46e45b026buh4vyw8",
        "listItems":
                [
                {"nameItem":"Random name item 1","code_cip":"34009275623967319","unitStock":17},
                {"nameItem":"Random name item 2","code_cip":"34009300409352486","unitStock":17}
                ]
    }

Sorry for my english, it's not my native language and thank you for your help ;)


Solution

  • I think JSONSerialization requires a dictionary or array as top level object.

    Use JSONEncoder instead.

    https://developer.apple.com/documentation/foundation/jsonencoder