How To Exclude From JSON Encoding And Decoding

You at least had to create dynamically instance of some class from JSON. All you have to do is add a Codable protocol to your struct declaration. It’s a very common operation.

Let’s say you have a simple struct Country with few fields.

struct Country: Codable {
    var name: String
    var size: Int
    var population: Int
}

Then you create an instance of it.

let country = Country(name: “New Country”, size: 404, population: 100000)

Then using JSONEncoder encoding it and printing the result you know what to expect.

let encodedData = try! JSONEncoder().encode(country)
print(String(data: encodedData, encoding: .utf8))

Output

Optional(“{\”name\”:\”New Country\”,\”size\”:404,\”population\”:100000}”)

However, what to do if there is a filed that you don’t want to include in JSON string?

Let’s say you want to have only name and size fields in JSON.

First, you need to set an initial value for the population. It’s required to decode from JSON to a struct.

var population: Int = 0

Then, inside Country struct add enum CodingKeys which inherits from CodingKey. Inside it list fields name you want to include during encoding.

enum CodingKeys: CodingKey {
    case name
    case size
}

Now, when you use the same code as previously then JSON string won’t have the population field.

let country = Country(name: “New Country”, size: 404, population: 100000)

, size: 404, population: 100000)

let encodedData = try! JSONEncoder().encode(country)
print(String(data: encodedData, encoding: .utf8))

Output

Optional(“{\”name\”:\”New Country\”,\”size\”:404}”)

It works in the same with JSONDecoder.