2
votes

Currently struggling how to use Decodable. I've done some googling to the errors I'm getting but I still believe that the way i'm structuring the structs isn't correct but it seems to make sense to me.

I've also tried using optionals

In the error that I've posted at the end, I'm confused about the reference to the Double type. As I don't have any type or anything int he response that uses a double.

(I'm also able to serialize the json reponse using the old swift method of casting the data as dictionaries - [String : Any]. But I'd like to use the modern/updated approach.)

JSON Response

    {"NEWS":
  [
    {
      "DATE":"2018-10-13T03:56:06+1000",
      "SOURCE":"smh.com.au",
      "BLURB":"Assistant Treasurer Stuart Robert says he has repaid $37,975 of \"excess usage charges\" in home internet bills footed by taxpayers.",
      "ID":102347,
      "TITLE":"Stuart Robert pays back $38,000 in excessive home internet charges"
    },
    {
      "DATE":"2018-10-12T18:00:38+1000",
      "SOURCE":"itwire.com",
      "BLURB":"The CVC costs set by the NBN Co make it very difficult for ISPs to offer gigabit connections to more than a select band of customers who are willing to sign up in numbers and pay slightly more than other speed tiers, according to one ISP who caters to this type of consumer.",
      "ID":102343,
      "TITLE":"NBN gigabit connections will remain mostly a pipe dream"},
    {
      "DATE":"2018-10-12T09:48:43+1000",
      "SOURCE":"computerworld.com.au",
      "BLURB":"The Department of Home Affairs has rejects calls to include independent judicial oversight of the decision to issue Technical Assistance Notices and Technical Capability Notices as part of proposed legislation intended to tackle police agencies’ inability to access encrypted communications services.",
      "ID":102342,
      "TITLE":"Home Affairs rejects calls for additional safeguards in ‘spyware’ law"
    },
    {
    "DATE":"2018-10-11T12:16:05+1000",
    "SOURCE":"itnews.com.au",
    "BLURB":"NBN Co is hoping to “speed up” building works on the fibre-to-the-curb (FTTC) portion of its network as it tries to make up lost ground.",
    "ID":102334,
    "TITLE":"NBN Co says fibre-to-the-curb build is more complex that it hoped"
    },
  ]
}

CODE

struct Root: Decodable {
    let news: [News]?

    enum CodingKeys: String, CodingKey {
        case news = "NEWS"
    }

}

struct News: Decodable {
    let date: Date
    let source, blurb: String
    let id: Int
    let title: String

    enum CodingKeys: String, CodingKey {
        case date = "DATE"
        case source = "SOURCE"
        case blurb = "BLURB"
        case id = "ID"
        case title = "TITLE"
    }
}

Serialization

URLSession.shared.dataTask(with: url) { (data, response, err) in  
guard let dataStr = data else {
            return
        }
do {
    let root = try JSONDecoder().decode(Root.self, from: dataStr) //error is caught here
    guard let r = root else { return }
    print(r.news)
} catch let err {
    print("JSON Error - \(err)")
}
}.resume()

Error

error serializing json typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "NEWS", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "DATE", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))

2

2 Answers

4
votes

This is because the default coding strategy for Date is double (seconds since epoch). You can change the default strategy to iso8061 or anything custom. For example, you can set the date formatter in your decoder like so:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
0
votes

Putting the JSON into Quicktype gives me an extra comma error. Unless there's more nodes to the json file? So make sure about that first. At first glance, I could be wrong, but I think you have to format the DATE to exactly match.