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 Parsing to Non-Primitive Types Parsing Dates

I'm getting a "Date string does not match format expected by formatter." error when I type in the code in xCode

I set the type of the publishDate variable to "Date" like it says in the video, and the only thing that works is

decoder.dateDecodingStrategy = .iso8061

When I use the code

let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
decoder.dateDecodingStrategy = .formatted(formatter)

I get the error

Can you post all of your code please.

ok, whole code

import Foundation

let json = """
{
    "title": "Harry Potter and the sorcerer's stone",
    "url": "https:\\/\\/openlibrary.org\\/books\\/OL26331930M\\/Harry_Potter_and_the_sorcerer's_stone",
    "publish_date": "1997-06-26T00:00:00+0000",
    "text": "VGhpcyBpc24ndCByZWFsbHkgdGhlIGNvbnRlbnRzIG9mIHRoZSBib29r",
    "rating": 4.9

}
""".data(using: .utf8)!

struct Book: Codable {
    let title: String
    let url: URL
    let publishDate: Date
    private let text: Data
    let rating: Double

    var contents: String {
        return text.stringDescription
    }
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
//decoder.dateDecodingStrategy = .iso8601

let formatter = DateFormatter()
formatter.dateFormat = "MMMM dd, yyyy"
decoder.dateDecodingStrategy = .formatted(formatter)
decoder.dataDecodingStrategy = .base64
decoder.nonConformingFloatDecodingStrategy = .convertFromString(positiveInfinity: "+Infinity", negativeInfinity: "-Infinity", nan: "NaN")

let potter = try! decoder.decode(Book.self, from: json)

potter.title
potter.url
potter.publishDate
potter.contents
potter.rating

1 Answer

Yes your dates format does not match. You missed the part about changing it. He was demonstrating changing the format received forcing you to use a custom formatter.

let json = """
{
    "title": "Harry Potter and the sorcerer's stone",
    "url": "https:\\/\\/openlibrary.org\\/books\\/OL26331930M\\/Harry_Potter_and_the_sorcerer's_stone",
    "publish_date": "June 26, 1997",

    "text": "VGhpcyBpc24ndCByZWFsbHkgdGhlIGNvbnRlbnRzIG9mIHRoZSBib29r",
    "rating": 4.9

}
""".data(using: .utf8)!

Dang, how did I miss that. Thanks dude!

Yeah no problem.