Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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)

employee.name
employee.id
employee.role
employee.startDate

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

let encodedEmployee = try! encoder.encode(employee)
print(encodedEmployee.stringDescription)

1 Answer

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

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