Convert date format from json data in the model an

2019-09-21 08:32发布

问题:

Here in my model I have a few struct to handle the data from server

struct Articles: Decodable {
var content : [ArticleData]

}

struct ArticleData: Decodable {
var title: String
var date_time: Date
var image: String
}

From the jason, I get a date, it's like that:

 "date_time": 1524842056.035,

First question: I set the type of this type in model Date as you see in ArticleData, it that correct?

Then I read this json in the model something like that:

  guard let json = try? JSONDecoder().decode(Articles.self, from: data!) else {
   completion(.failure(loginError.networkError))
                return
            }

    completion(.success(json.content))

As you can see, I get an array from server json.content that contain title, date_time and image. I want to convert it here in the model and pass everything in completion to the controller. could you help me on that?

Thanks :)

回答1:

you can use type 'String' for your date and then convert it using dateFormatter or, use 'dateDecodingStrategy' function in your decoder. for passing the data you are already doing the correct thing. where ever you call the method you can get the model.