【问题标题】:what is the best way to save json data in swift model在快速模型中保存 json 数据的最佳方法是什么
【发布时间】:2019-11-01 08:33:57
【问题描述】:

我之前发表过一篇关于如何将 json 数据保存在模型 here 中的帖子。 很好,现在我正在用 swift 在 iOS 上开发一个项目,我遇到了以下问题,有时数据库管理员会不断更改列的名称,我只在 Alamofire 的帮助下使用服务,要在模型中保存数据,请使用 camal 案例和蛇案例,目前一切都很好,但我想知道在 swift 模型中保存 json 数据的最佳方法是什么,以我的经验在 Android 中,我使用了 @Serializename 的改造,效果很好,因为如果修改了服务的 json 属性,我只需要更新一行代码并且我的变量可以保持不变,这有助于我保持更好的秩序和它使它具有可扩展性。

在某些情况下,json 会来找我。

{
 "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"
}

它会以以下方式生成我的模型。

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

这里的问题是我的变量必须适合我使用JSONDecoder()convertFromSnakeCase的json,我不能自己定义它们。

在 java android 中我只需要这样做。

@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;

我只需要创建 get 和 set 就可以使用模型了。 我需要知道如何在 swift 中做同样的事情,也许是一个库,可以帮助我以与我在 android 中相同的方式存储数据 json。 任何意见将不胜感激。

【问题讨论】:

    标签: ios json swift model-view-controller model


    【解决方案1】:

    使用 Alamofire,您将获得一个键值,Dictionary<String,Any>[String:Any]

    因此,您可以对字典执行以下操作:

    var myProduct : Product?
    if let price = myDictionary["price"] as? String{
        myProduct.price = price
    }
    

    通过该示例,您可以创建一个方法来将整个 JSON 映射到您的结构中。也许如果你想让它更具可扩展性,你可以使用 String 原始值创建一个枚举并将其用作字典的键,例如:

    enum productProperty : String{
        case Price = "price"
    }
    var myProduct : Product?
    if let price = myDictionary[productProperty.Price] as? String{
        myProduct.price = price
    }
    

    并且可能创建一个更复杂的类来遍历字典并使用枚举检查键,但该实现取决于您自己的技能。

    编辑1:

    要与alamofire一起使用,你需要获取请求的jsonResponse,有些像这样:

    .request(yourURL, method: .get, parameters: yourParameter).responseJSON(options: .allowFragments , completionHandler: { response in
        if let object = response.result.value as? Dictionary<String,Any> {
            yourMethodToSave(object)
        }
    })
    

    yourMethodToSave(_ object: Dictionary&lt;String,Any&gt;) 中,您需要将逻辑放在上面。

    Ps:@sendtobo 的答案有一个枚举示例,我告诉您可以为您的对象使用更具可扩展性的映射

    【讨论】:

    • 你能用 SwiftyJson 吗?
    • 我如何将它与 alamofire 结合使用?因为它表明所有答案 json 都保存在模型中
    • @dbenitobaldeon 我已经编辑了答案,再看一遍
    【解决方案2】:

    请随意使用我的要点: Storage

    你可以这样使用它:

    
    let fileName = "Product.json"
    
    extension Product {
        func store() {
            Storage.store(self, to: .documents, as: fileName)
        }
    
        static func retrieve() -> Product? {
            guard let product =  Storage.retrieve(fileName, from: .documents, as: Product.self) else {
                return nil
            }
            return product
        }
    }
    

    【讨论】:

      【解决方案3】:

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

      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"
          }
      }
      

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

      【讨论】:

      • 这看起来很有趣,我会证明的。类似于另一个答案
      • 我如何将它与 alamofire 结合使用?因为它表明所有答案 json 都保存在模型中
      猜你喜欢
      • 2018-03-17
      • 2014-08-22
      • 2014-08-04
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 2020-11-03
      • 2021-08-19
      相关资源
      最近更新 更多