0

I have a struct like -

struct Attachment : Codable {
var reviewA : [String]?
var reviewB : String?
}

Now earlier the API was returning string only which I can set in reviewB but now it has 3 cases. It can either be empty string (""), array of strings(["",""]) or single string ("dummy"). Now, my console gives error - Expected to decode String but found an array instead

How should I resolve it?

TheTravloper
  • 236
  • 5
  • 16
  • 1
    https://stackoverflow.com/questions/46279992/any-when-decoding-json-with-codable – Roman Ryzhiy Sep 22 '20 at 11:55
  • Do you control the API? You should make `reviewB` always returns an array of strings. Having them empty doesn't make much sense though, what dos it mean if a review is `""`? – Alexander Sep 22 '20 at 12:34

1 Answers1

0

You can all time use array

let json = """
{
    "reviewA": ["H"],
    "reviewB": "H"
}
"""

let jsonData = json.data(using: .utf8)!

struct Attachment: Codable {
    var reviewA:    [String]?
    var reviewB:    [String]?
    
    private enum Keys: String, CodingKey {
        case reviewA
        case reviewB
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: Keys.self)
        
        self.reviewA = try container.decode([String].self, forKey: .reviewA)
        
        if let arr = try? container.decode([String].self, forKey: .reviewB) {
            self.reviewB = arr
        } else {
            let str = try container.decode(String.self, forKey: .reviewB)
            self.reviewB = [str]
        }
    }
}


let model = try! JSONDecoder().decode(Attachment.self, from: jsonData)
print(model)