Swift4.0 Codable使用
摘自:
Everything about Codable in Swift 4
//
// main.swift
// TestCodable
//
// Created by Adrift on 2017/11/13.
// Copyright © 2017年 Adrift. All rights reserved.
//
import Foundation
struct Obj: Codable {
struct MenuItem: Codable {
let value: String
let onClick: String
enum CodingKeys: String, CodingKey {
case value
case onClick = "onclick"
}
}
struct Popup: Codable {
let menuItem: [MenuItem]
enum CodingKeys: String, CodingKey {
case menuItem = "menuitem"
}
}
struct Menu: Codable {
let id: String
// let id: String = "hello.id" 通过设置默认值的方式,可以忽略属性赋值
let value: String
let popup: Popup
}
let menu: Menu
}
let str = """
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}
}
"""
if let data = str.data(using: String.Encoding.utf8) {
do {
let obj = try JSONDecoder().decode(Obj.self, from: data)
print(obj.menu.id)
} catch {
print(error)
}
}
//{
// "size":{
// "width":150,
// "height":150
// },
// "title":"Apple"
//}
//转成
//{
// "title":"Apple",
// "width":150,
// "height":150
//}
struct Size: Codable {
var width: Double
var height: Double
}
struct Photo {
var title: String
var size: Size
enum CodingKeys: String, CodingKey {
case title = "name"
case width
case height
}
}
extension Photo: Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(title, forKey: .title)
try container.encode(size.width, forKey: .width)
try container.encode(size.height, forKey: .height)
}
}
extension Photo: Decodable {
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
title = try values.decode(String.self, forKey: .title)
let width = try values.decode(Double.self, forKey: .width)
let height = try values.decode(Double.self, forKey: .height)
size = Size(width: width, height: height)
}
}
--EOF--