1

I'm refactoring some projects where I'd previously used third-party JSON parsers and I've encountered a goofy site that returns a boolean as a string.

This is the relevant snippet from the JSON response:

{
    "delay": "false",
    /* a bunch of other keys*/
}

My struct for Decoding looks like this:

struct MyJSONStruct: Decodable {
  let delay: Bool
  // the rest of the keys
}

How would I convert the string returned in the JSON response into a Bool to match my struct in Swift 4? While this post was helpful, I can't figure out how to turn a string response into a boolean value.

Adrian
  • 16,233
  • 18
  • 112
  • 180

2 Answers2

10

Basically you have to write a custom initializer but if there are many good keys but only one to map from a type to another a computed property might be useful

struct MyJSONStruct: Decodable {
   var delay: String
   // the rest of the keys

   var boolDelay : Bool {
       get { return delay == "true" }
       set { delay = newValue ? "true" : "false" }
   }
}
vadian
  • 274,689
  • 30
  • 353
  • 361
1

you need to set the boolEncoding: .literal in the URLEncoding initializer.

boolEncoding: .literal