[Solved] how to encode this JSON reply from Food API


You have some response and this response’s value is most likely of type Data, so you need to decode it to some Swift type.


Since Swift 4 you can easily use Decodable protocol for decoding Data to your custom model conforming to this protocol.

So let’s create simple struct for simple json

Json:

let data = Data("""
{
    "property": "someName"
}
""".utf8)

Model:

struct Model: Decodable {
    let property: String
}

Each property also has to be Decodable, so if you have different decodable struct, you can use it as property’s type and you can even use it for array of this type, or for example some dictionary

Json:

let data = Data("""
{
    "items": [
        { "title": "name1" },
        { "title": "name2" },
        { "title": "name3" }
    ]
}
""".utf8)

Model:

struct Model: Decodable {
    let items: [Item]
}

struct Item: Decodable {
    let title: String
}

Do you see that pattern? So try to implement it in your case by yourself.


Now the last part: decoding. For decoding Data you can simply use JSONDecoder and its decode method. Just specify type of output and pass Data object

Note that decoding can throw error, so you should put it to do-try-catch block

guard let data = response.result.value else { ... }

do {
    response.result.value!
    let models = try JSONDecoder().decode([Model].self, from: data)
} catch { print(error) }

solved how to encode this JSON reply from Food API