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?

2
  • 1
    stackoverflow.com/questions/46279992/… Commented Sep 22, 2020 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 ""? Commented Sep 22, 2020 at 12:34

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

There is no need to implement enum Keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.