Dylan
Dylan

Reputation: 1348

Swift how to know if json key is null or no key?

I have a struct that reflects the data from nesed JSON with nilable variables.

struct JsonReceived: Decodable {
    let data: JsonReceivedData
}

struct JsonReceivedData: Decodable {
    let key1: String?
    let key2: String?
    let key3: String?
    let key4: String?
    let key5: String?
}

then I encode the json by JSONDecoder and send it's data to the function.

let res = try JSONDecoder().decode(JsonReceived.self, from: data)

self.addData(res.data.key1)
self.addData(res.data.key2)
self.addData(res.data.key3)
self.addData(res.data.key4)
self.addData(res.data.key5)

The problem is, sometimes the JSON data was look like this

{
    "data": {
        "key1": "value1",
        "key3": "value3",
        "key5": null,
    }
}

and I don't want to send the data from the function if the key doesn't exist,

As you can see in my JSON sample, there is no key2 and key4 key value pair, so I don't want to send them to the function, the key5 is null but still it have a key, so I want it to send to the function even if it's null.

I want the output will something like this.

if isHaveAkeyFromJSON(res.data.key2) {
    self.addData(res.data.key2)
}

Upvotes: 0

Views: 1010

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51892

If you don't need the structs for other things then you can decode and call your method in once

struct JsonReceived: Codable {
    let data: [String: String?]

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        data = try container.decode([String: String?].self, forKey: .data)
        data.values.forEach {
            self.addData($0)
        }
    }
}

Upvotes: 1

HalR
HalR

Reputation: 11073

res doesn't know how it was created. Key's with values have valued, and those that don't don't. You need to look at the receive JSON again if you want that information.

let testDictionary = try decoder.decode([String: String?].self, from: data)

then test the dictionary for the key:

if testDictionary.keys.contains(res.key2) {
    self.addData(res.key2)
}

Upvotes: 1

Related Questions