1

Is there a way to decode a JSON that is a list of objects when some of these objects can't be decoded properly? Let's say I have a enum with 2 possible values foo and bar but all of sudden backend starts to return another possible option for that field (let's say other).

Looking to the example below, first part is fine. What I wanted is to have in the second part, a list containing 1 element (foo), instead of nil.

import Foundation

enum Value: String, Codable {
    case foo
    case bar
}

struct Object: Codable {
    let value: Value
}

let dataList = "[{\"value\":\"foo\"}, {\"value\":\"bar\"}]".data(using: .utf8)!
let objectList = try? JSONDecoder().decode([Object].self, from: dataList) // [{foo}, {bar}]

let anotherDataList = "[{\"value\":\"foo\"}, {\"value\":\"other\"}]".data(using: .utf8)!
let anotherObjectList = try? JSONDecoder().decode([Object].self, from: anotherDataList) // nil

// is there a way to have this ^ as [{foo}] instead of nil?
Gustavo Barbosa
  • 1,340
  • 1
  • 17
  • 27
  • Here's a solution from a duplicate thread, for anyone who comes across this: https://stackoverflow.com/a/46369152/4039079 – Dafurman Jun 13 '18 at 22:10

0 Answers0