Swift学习之Json转Model

目前主流的Json转Mode框架:

  • SwiftyJSON Github 上 Star 最多的 Swift JSON 解析框架

  • ObjectMapper 面向协议的 Swift JSON 解析框架

  • HandyJSON阿里推出的一个用于 Swift 语言中的 JSON 序列化/反序列化库。

  • KakaJSON mj新写的一个转模型工具

  • JSONDecoder Apple 官方推出的基于 Codable 的 JSON 解析类

这里主要总结下JSONDecoder的使用,毕竟亲儿子的前途要更光明些

官方介绍

文档

下面的示例展示了如何从JSON对象解码一个GroceryProduct类型实例。该类型采用Codable,因此它可以使用JSONDecoder实例进行解码

// 定义模型名称
struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

    let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

// 对data数据进行解析
let decoder = JSONDecoder()
let product = try? decoder.decode(GroceryProduct.self, from: json)

// 读取model中数据
print(product?.description ?? "nil")

func decode(_ type: T.Type, from data: Data) throws -> T where T : Decodable

  • type json解析之的类型
  • data 要解析的数据

复杂类型数据结构使用

当出现多层嵌套时

    
    let json2 = """
{
    "id": 1001,
    "name": "Durian",
    "points": 600,
    "parameters": {
        "size": "80*80",
        "area": "Thailand",
        "quality": "bad"
    },
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!

这时候我们的模型类做相应的struct处理
如果key的名字想自定义,可通过CodingKey来实现转换
这里假设quality为有限类型时,可通过枚举来显示,更加直观


struct GroceryProduct: Codable {
    var ID: Int
    var name: String
    var points: Int?
    var description: String?
    var parameters: Parameters?
    
    enum CodingKeys: String, CodingKey {
        case ID = "id"
        case name
        case points
        case description
        case parameters
    }
  
    struct Parameters: Codable {
        var size: String?
        var area: String?
        var quality: Quality?
    }
    
    enum Quality: String, Codable {
        case good, caporal, bad
    }
}

解析和调用

do {
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let product2 = try decoder.decode(GroceryProduct.self, from: json2)
    print(product2.parameters?.quality ?? "unknown")

} catch let error {
    print(error)
}

列表数据

模拟请求列表数据

{
    "code": 10000,
    "msg": "请求成功",
    "datas" : [
        {
            "id": 1001,
            "name": "Durian",
            "points": 600,
            "parameters": {
                "size": "80*80",
                "area": "Thailand",
                "quality": "bad"
            },
            "description": "A fruit with a distinctive scent."
        },
        {
            "id": 1002,
            "name": "Apple",
            "points": 600,
            "parameters": {
                "size": "80*80",
                "area": "China",
                "quality": "good"
            },
            "description": "A round fruit with shiny red or green skin and firm white flesh."
        },
        {
            "id": 1003,
            "name": "Arange",
            "points": 600,
            "parameters": {
                "size": "80*80",
                "area": "China",
                "quality": "caporal"
            },
            "description": "A round citrus fruit with thick reddish-yellow skin and a lot of sweet juice."
        },
        {
            "id": 1004,
            "name": "Banana",
            "points": 600,
            "parameters": {
                "size": "80*80",
                "area": "Malaysia",
                "quality": "good"
            },
            "description": "A long curved fruit with a thick yellow skin and soft flesh, that grows on trees in hot countries."
        }
   ]
}

创建model类

struct ProductListModel: Codable {
    var code: Int
    var msg: String
    var datas: [GroceryProduct]
}

请求数据源并解析

 guard let urlPath = Bundle.main.path(forResource: "ProductList", ofType: "json") else { return }
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: urlPath))
            let jsonData: Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            print("present = ", jsonData)
            
            let product3 = try decoder.decode(ProductListModel.self, from: data)
            print(product3.datas[2].ID)

        } catch let error {
            print(error)
        }

demo

注意事项

  • 数据类型一定要匹配,否则解析失败

你可能感兴趣的:(Swift学习之Json转Model)