Not just JSON to Model

  • string <-> model
  • data <-> model
  • dict <-> model

In the actual development of Swift, JSON -> Model does not need to use the third-party POD, the official Coadble can meet most of the situation, sometimes we need not only jsonstr -> Model, sometimes also need, Model – > string (data \ dict).

So I packaged it into the SpeedySwift acceleration library.

Use the sample

show my code

    let model = jsonstr.toModel(GroceryProduct.self)
    
    let data = model?.toData()
    
    let dict = model?.toDict()
    
    let dict2 = data?.toDict()
    
    let model2 = data?.toModel(GroceryProduct.self)
Copy the code

How do I block a field in Codable?

    struct Parameters: SSCoadble {
        var size: String?
        var area: String?
        var quality: Quality?
        If you don't have this property in JSON but want to use it yourself, you can add lazy and initialize it
        lazy var isSelected:Bool = false
    }
Copy the code

For example, in the code above, isSelected is not represented in JSON, but is my business tag.

I could block Codable from parsing this field by adding lazy and initializing it

How to map attributes

Different languages have different naming methods, such as big hump, small hump, underline, and maybe the server and our client have different names.

struct GroceryProduct: Codable {
    var ID: Int
    var name: String
    var points: Int?
    var description: String?
    
    enum CodingKeys: String.CodingKey {
        case ID = "id"
        case name
        case points
        case description
    }
}
Copy the code

For example, id, id in the above structure.

We need to map in the enum CodingKeys: String, CodingKey method.

Extend Codable

Increase its ability to convert to dictionaries and Data

public protocol SSCoadble: Codable{
    func toDict(a)->Dictionary<String.Any>?
    func toData(a)->Data?
}
Copy the code

Add default implementations of toDict() and toData() for SSCoadble

public extension SSCoadble{
    
    func toData(a)->Data? {return try? JSONEncoder().encode(self)}func toDict(a)->Dictionary<String.Any>? {
        if let data = toData(){
            do{
                return try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]}catch{
                 debugPrint(error.localizedDescription)
                return nil}}else{
            debugPrint("model to data error")
            return nil}}}Copy the code

There are other small conversions between JSON, data, string, and dict that can be found in SpeedySwift, my open source library.