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).

Is it what you pass to encoder

[["type": "SOME_TYPE_1"], ["type": "SOME_TYPE_2", "count": 2]]

try:

[["type": "SOME_TYPE_1", "count": nil], ["type": "SOME_TYPE_2", "count": 2]]

Have a look here for details: https://developer.apple.com/forums/thread/105091

JSONSerialization is not the right JSON API to use with Codable or for Swift-only types generally. It’s designed for older Objective-C types (NSDictionary, etc.) and can’t handle Swift struct types. Instead, use JSONEncoder with Swift types; see here.

Encoding struct optional field to JSON
 
 
Q