Q:

Vapor3 JSON encode & Decode

I'm having to use a FoundationDB database for a project. It stores data as a key:value pair stored as Bytes. I want to store a JSON object mapped to a struct I have. I want to be able save the data as an encoded JSON object and then be able to recreate the JSON object by reading the value Bytes from the DB.
In my CreateRecord function I pass a JSON in a request and use it to create my Country object. I need to convert the type Data into Bytes to store it.
So far I have come up with this.
let data: Bytes = try JSONEncoder().encode(country).base64URLEncodedString()

Then, when I read the record from the database I need to be able to reverse the process to create my Country object from the Bytes that store the JSON.
let mycountry:Country = try decoder.decode(Country.self, from: Data(bytes: DBrecord.value) )

The struct is:
struct Country: Content {
    var country_name: String
    var timezone: String
    var default_PickUp_location: String = ""
    init(country_name: String, timezone:String, default_PickUp_location: String?) {
        self.country_name = country_name
        self.timezone = timezone
        if default_PickUp_location != nil {
            self.default_PickUp_location = default_PickUp_location!
        }
    }
}

And a sample JSON is:
{ "country_name" : "Denmark", "timezone" : "Europe\/Copenhagen", "default_pickup_location" : "Copenhagen" }

I cannot seem to be able to reverse the conversion. Any help please?

A:

In your JSON, you use default_pickup_location and in your struct you use default_PickUp_location. You need to settle on one version.
To discover this, I used the following test route:
router.get("json")
{
    request throws -> String in
    let json = "{ \"country_name\" : \"Denmark\", \"timezone\" : \"Europe/Copenhagen\", \"default_pickup_location\" : \"Copenhagen\" }"
    let encoder = try JSONDecoder().decode(Country.self, from: json)
    return "It works"
}

It returned:

{"error":true,"reason":"Value required for key
  'default_PickUp_location'."}

