-->

Convert string JSON response to a boolean using Sw

2020-08-09 05:43发布

问题:

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.

回答1:

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" }
   }
}


回答2:

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

boolEncoding: .literal