Post

Replies

Boosts

Views

Activity

Encoding struct optional field to JSON
Hi! I having trouble with encoding optional field of structure to send it to my server. Here's this struct: struct Defect: Codable { var type: String = "" var count: Int? = nil } When server returns data like this [["type": "SOME_TYPE_1"], ["type": "SOME_TYPE_2", "count": 2]] app successfully decodes is, but when I'm trying to encode the same data with func request(json: Dictionary<String, Any> = [:]) { // some code ... request.httpBody = try JSONSerialization.data(withJSONObject: json) // some other code ... } func updateObject(defects: Array<Defect>) { // some code ... let json: [String: Any] = ["comment": comment, "defects": defects] request(/*some params*/ json: json) // some code ... } I got error NSException * "Invalid type in JSON write (__SwiftValue)" in this string: request.httpBody = try JSONSerialization.data(withJSONObject: json) Struct's fields values at this moment are: json["defects"][0].type = "SOME_TYPE_1" json["defects"][0].count = nil json["defects"][1].type = "SOME_TYPE_2" json["defects"][1].count = 2 Please give me a guidance how to solve this problem. Maybe using of encode(to:) may help me (I'm novice, and didn't try it yet).
2
0
549
Nov ’23