Json4swift模型类

时间:2017-01-25 10:19:58

标签: swift model

我是swift的新手,使用json4swift工具制作模型类。我想知道如何从模型类中获取数据,我设法使用下面的代码将项目映射到模型类。

  let responseModel = Json4Swift_Base(dictionary: searchResultsData)

我的json回答了以下问题:

{
  "success": true,
  "categorys": [
    {
      "categoryId": 1,
      "categoryName": "Electricians                                      "
    },
    {
      "categoryId": 2,
      "categoryName": " Drivers                                          "
    },
    {
      "categoryId": 3,
      "categoryName": " Plumbers                                         "
    },
    {
      "categoryId": 4,
      "categoryName": "Carpenters                                        "
    },
    {
      "categoryId": 5,
      "categoryName": "Automobile works                                  "
    }
  ]
}

Json4swift工具制作了两个类,即Json4Swift_Base和Categorys类。我需要从模型类中获得。

1 个答案:

答案 0 :(得分:1)

如果你想学习Swift,我建议你忘记json4swift。

首先,您必须构建自己的模型:CategoryResponse

类别:

struct Category {
    let id: Int
    let name: String
}

回应:

struct Response {
    let success: Bool
    let categories: [Category]
}

其次,您希望使用JSON初始化模型。我们将为此创建一个协议:

typealias JSONDictionary = [String : Any]

protocol JSONDecodable {
    init?(dictionary: JSONDictionary)
}

您的模型必须实现此协议,因此我们添加了扩展程序:

类别扩展名:

extension Category: JSONDecodable {
    init?(dictionary: JSONDictionary) {
        guard let id = dictionary["categoryId"] as? Int,
            let name = dictionary["categoryName"] as? String else {
                return nil
        }
        self.id = id
        self.name = name
    }
}

回复延期:

extension Response: JSONDecodable {
    init?(dictionary: JSONDictionary) {
        guard let success = dictionary["success"] as? Bool,
            let jsonCategoriesArray = dictionary["categorys"] as? [JSONDictionary] else {
                return nil
        }
        self.success = success

        self.categories =
            jsonCategoriesArray.flatMap{ jsonCategoryDictionary in
                Category(dictionary: jsonCategoryDictionary)
            }
    }
}

现在,你可以写:

let response = Response(dictionary: jsonResponse)

if let response = response {
    let success = response.success
    let categories = response.categories
    let firstCategory = categories[0]
    // ...
}