Swift Codable
import Foundation
let jsonString = """
{
"title": "Blah",
"age": 12,
"gender": "F",
"body":{
"weight": 60,
"height": 180
}
}
"""
struct Gender
{
var sex: String!
}
struct Person: Codable
{
// 一般配對
var name: String!
var age: Int!
// JsonString->Object 一層變兩層
var gender: Gender! = Gender()
// JsonString->Object 兩層變一層
var weight: Int!
var height: Int!
enum CodingKeys: String, CodingKey
{
case name = "title"
case age
case gender
case body
}
enum BodyKeys: String, CodingKey
{
case weight
case height
}
init(from decoder: Decoder) throws
{
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
age = try container.decode(Int.self, forKey: .age)
gender.sex = try container.decode(String.self, forKey: .gender)
let body = try container.nestedContainer(keyedBy: BodyKeys.self, forKey: .body)
weight = try body.decode(Int.self, forKey: .weight)
height = try body.decode(Int.self, forKey: .height)
}
func encode(to encoder: Encoder) throws
{
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(age, forKey: .age)
try container.encode(gender.sex, forKey: .gender)
var body = container.nestedContainer(keyedBy: BodyKeys.self, forKey: .body)
try body.encode(weight, forKey: .weight)
try body.encode(height, forKey: .height)
}
}
結果
Last updated