Парсинг json файла с помощью протокола Decodable


#1

Как сказать экскоду при парсинге json формата, что на некоторые свойства класса или структуры, которые отсутствуют в json запросе не стоит обращать внимания ?

приведу пример чтобы более менее понятно была суть вопроса

class Question: Decodable {
    public private(set) var number: Int?
    public private(set) var description: String?
    public private(set) var image: String?
    public private(set) var answers: [String]?
    public private(set) var answer: String?
    public private(set) var annotation: String?
    public private(set) var isPassed = false
}

свойства isPassed не в json, как его по дефолту устанавливать при парсинге объектов и их создании?
Заранее спасибо за ответы или ссылка по данной теме.


#2

попробуй реализовать конструктор Decodable:


enum CodingKeys: String, CodingKey {
		case number
	}

init (from decoder: Decoder) throws {
  let container = try decoder.container(keyedBy: CodingKeys.self)
  number = try? container.decode(Int.self, forKey: .number)
  //тут разбор остальных  свойств контейнера.
}		

#3

Да получилось, спасибо, вопрос закрыт.

просто нехотел писать энум и инициализатор, думал по дефолту сработает с инициализатором по умолчанию.
Выдавало ошибку - The data couldn’t be read because it is missing.
Получается нужно явно указывать какие свойства берутся из json.

вот финальный вид может кому пригодиться

import Foundation

class Question: Decodable {

    public private(set) var number: Int?
    public private(set) var description: String?
    public private(set) var image: String?
    public private(set) var answers: [String]?
    public private(set) var answer: String?
    public private(set) var annotation: String?
    public private(set) var isPassed = false
    
    enum CodingKeys: String, CodingKey {

        case number = "number"
        case description = "description"
        case image = "image"
        case answers = "answers"
        case answer = "answer"
        case annotation = "annotation"
    }

    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        number = try values.decodeIfPresent(Int.self, forKey: .number)
        description = try values.decodeIfPresent(String.self, forKey: .description)
        image = try values.decodeIfPresent(String.self, forKey: .image)
        answers = try values.decodeIfPresent([String].self, forKey: .answers)
        answer = try values.decodeIfPresent(String.self, forKey: .answer)
        annotation = try values.decodeIfPresent(String.self, forKey: .annotation)
    }
}