Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Parsing JSON Using Codable An Overview of Codable The CodingKey Protocol

Deysha Rivera
Deysha Rivera
5,088 Points

Error Parsing JSON using Codable when adding snake case

My code does not compile. I get an error saying my data is not valid JSON. Have tried to delete and add again, CMD+Q to restart the complier. It works if I remove the snake case data.

import Foundation

let json = """
    "name": "Pasan",
    "id": 1,
    "role": "Teacher"
    "start_date": "April 2012"
""".data(using: .utf8)!

struct Employee: Codable {
    let name: String
    let id: Int
    let role: String
    let startDate: String

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

let employee = try! decoder.decode(Employee.self, from: json)


let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase

let encodedEmployee = try! encoder.encode(employee)

1 Answer

Magnus Hållberg
Magnus Hållberg
17,232 Points

Your JSON is not valide, it is missing a comma after ("role": "Teacher").