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 trialDeysha Rivera
5,088 PointsError 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
17,232 PointsYour JSON is not valide, it is missing a comma after ("role": "Teacher").