0

在使用 Swift 4 解码 JSON 时,我想在解码期间将字符串转换为大写。JSON 将其存储为大写

例如

let title =  "I CANT STAND THE RAIN"
print(title.capitalized)

如何在解码过程中执行此操作,以便将字符串以大写形式存储在我的模型中?

唯一需要注意的是,我只想将 JSON(标题)中的一个属性大写,而不是其余的。

struct Book: Decodable {
    let title: String 
    let author: String
    let genre: String

    init(newTitle: String, newAuthor: String, newGenre: String) {
        title = newTitle
        author = newAuthor
        genre = newGenre
    }
}

let book = try! decoder.decode(Book.self, from: jsonData)
4

2 回答 2

1

您可以为您的结构提供您自己的自定义可解码初始化程序。

struct Book: Decodable {
    let title: String
    let author: String
    let genre: String

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        title = try values.decode(String.self, forKey: .title).capitalized
        author = try values.decode(String.self, forKey: .author)
        genre = try values.decode(String.self, forKey: .genre)
    }

    enum CodingKeys: String, CodingKey {
        case title, author, genre
    }
}
于 2018-09-01T23:37:42.933 回答
-1
jsonString.replace(/"\s*:\s*"[^"]/g, match => {
  return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})
于 2018-09-01T13:21:45.850 回答