0

In decoding JSON with Swift 4, I would like to convert a string during decoding into capital case. The JSON stores it as uppercase

For example

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

How can I do this during the decoding process so the string is stored as capitalized in my model?

The only caveat is that I only want to capitalize one of the properties in the JSON (title) not the rest of them.

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)
Ray Saudlach
  • 530
  • 1
  • 6
  • 19
  • Unrelated but with a `struct` you do not need to provide your own `init` to set values for all of the properties. A `struct` provides that for you by default. – rmaddy Sep 01 '18 at 23:21

2 Answers2

1

You can provide your own custom Decodable initializer for your struct.

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
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
-1
jsonString.replace(/"\s*:\s*"[^"]/g, match => {
  return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Debabrata
  • 124
  • 1
  • 10
  • 6
    Simply posting some code isn't terribly helpful. Can you explain your code? That way others can understand and learn from your answer instead of just copying & pasting some code from the web. – Robert Sep 01 '18 at 21:23