закодировать класс в одно значение, а не в словарь - PullRequest
0 голосов
/ 07 января 2020

С учетом классов:

class ComplementApp: Codable{
    let name: String
    let idSpring: String
}

class MasterClass: Encodable{
    let complement: ComplementApp
    ///Other propierties
}

Я хочу получить:

//Where "Some ID" is the value of complement.idSpring
{
   complement: "Some ID"
   //Plus the other properties
}

Не

{
   complement: {
      name: "Some Name",
      idSpring: "Some ID"
   }
   //Plus other properties
}

По умолчанию. Я знаю, что я могу сделать это, бросить функцию кодирования и CodingKeys в MasterClass, но у меня есть, как 20 других переменных, и я должен добавить 19 дополнительных ключей. Могу ли я добиться реализации CodingKeys в ComplementApp?

1 Ответ

1 голос
/ 07 января 2020

Этого можно добиться с помощью пользовательской реализации encode(to:):

class ComplementApp: Codable {
    let name: String
    let idSpring: String

    func encode(to coder: Encoder) throws {
        var container = coder.singleValueContainer()
        try container.encode(idSpring)
    }
}

Использование singleValueContainer приведет к тому, что ваш объект будет закодирован как одно значение вместо объекта JSON. И вам не нужно прикасаться к внешнему классу.

...