首页 > 解决方案 > what is the best way to save json data in swift model

问题描述

I previously made a post about how to save json data in a model here . Good now I am developing a project on iOS with swift, and I face the following problem, it happens that sometimes the database administrators change the names of the columns constantly, I only consume services with the help of Alamofire, to save data in models, use camal case and snake case, At the moment everything is fine but I would like to know what is the best way to save json data in a swift model, in my experience with Android I used retrofit with @Serializename and it worked great because if the json attribute of the service it was modified I only had to update a line of code and my variable could be kept the same, this helped me maintain a better order and it made it scalable.

In some cases the json comes to me.

{
 "price": "385.000000",
 "nameusser": null,
 "favorite": 43,
 "short_nameProduct": "Génifique Repair Sc",
 "description_product": "Génifique repair sc es la crema de noche antiedad de lancôme. Despiértese con una piel fresca y rejuvenecida con nuestra crema de noche.",
 "alt": null,
 "photo": "https://url/020021000112-1.png"
}

in swift it would generate my model in the following way.

struct Product : Codable {
    let price : String?
    let nameusser : String?
    let favorite : Int
    let shortNameProduct : [Product]
    let description : [Galery]
    let alt : Product
    let success : Bool
}

The problem here is that my variables must fit the json I get to use the JSONDecoder() and the convertFromSnakeCase, I can not define them myself.

while in java android I just have to do it like that.

@SerializedName("price")
private String price;
@SerializedName("nameusser")
private String name;
@SerializedName("favorite")
private Int favorite;
@SerializedName("short_nameProduct")
private String shortName;
@SerializedName("description_product")
private String descriptionProduct;
@SerializedName("altitude")
private String altitude;
@SerializedName("photo")
private String photo;

I just have to create the get and set and I would be ready to use the model. I need to know how to do in swift the same, maybe a library that helps me store data json in the same way that I do in android. Any comment would be very appreciated.

标签: iosjsonswiftmodel-view-controllermodel

解决方案


最好的方法是使用编码键:

struct Product : Codable {
    let price : String?
    let nameusser : String?
    let favorite : Int
    let shortNameProduct : [Product]
    let description : [Galery]
    let alt : Product
    let success : Bool

    enum CodingKeys: String, CodingKey {
        case price = "price"
        case nameusser = "nameusser"
        case favorite = "favorite"
        case shortNameProduct = "short_nameProduct"
        case description = "description_product"
        case alt = "alt"
        case success = "success"
    }
}

枚举案例的名称必须与结构上的属性名称匹配。这样您就可以定义您想要的任何键,而无需编写任何自定义编码或解码代码。


推荐阅读