MENU

Swift 4 JSON 解析进阶

在前面 JSON 解析指南中,有网友提出了在使用类继承时默认实现存在问题。这个问题触发了更多的思考和学习,对他致以最高的谢意。接下来,我就从这个问题开始进一步介绍 Swift 4 中 JSON 解析。

2017-08-18-01.jpeg

问题回顾

当我们使用类集成时,子类在解析只有继承而来的属性有值而本身的属性则都为 nil

enum BeerStyle: String, Codable {
    case ipa
    case stout
    case kolsch
}

class Wine: Codable {
    var abv: Float?
}

class Beer: Wine {
    var name: String?
    var brewery: String?
    var style: BeerStyle?
}

let jsonDic = ["name":"beer", "brewery":"100","abv":10.0,"style":"ipa"] as [String : Any]

let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
let decode = JSONDecoder()
do {
    let beer = try decode.decode(Beer.self, from: jsonData)
    print("解析成功:\(beer)")
} catch  {
    print("解析失败:\(error)")
}

上面代码运行的最终结果是:解析成功但是 namebrewerystyle 三个属性全部为 nil 。显然,这不是我们想要的结果。这是 Swift 4 中一个有待改进的地方,Codable 默认实现无法覆盖继承这种情况。具体代码详解评论部分。其中涉及的主要关键点:自定义编码自定义解码

接下来,我就对前文进行一些补充。

深度自定义

虽然 Codable 的默认实现足够应付大多数情形了,但是有时候我们还是存在一些自定义需求。为了处理这类自定义问题,我们就必须自己覆盖默认的 Codable 实现。

自定义编码

接下来,我们看如何进行编码的自定义实现。假设,我们需要对上篇文章中 Beer Model 进行如下拓展:

struct Beer : Codable {
    //...
    let createdAt: Date
    let bottleSizes: [Float]
    let comments: String?
    
    //...
}

但是,我们希望在编码时改变命名风格将 createdAt 映射为 created_at 同时将 bottleSizes 映射为 bottle_sizes,也就是形如以下这种 JSON 格式:

{
  "comments" : null,
  "style" : "ipa",
  "brewery_name" : "Saint Arnold",
  "created_at" : "524716294.793119",
  "alcohol_by_volume" : 8.8999996185302734,
  "bottle_sizes" : [
    12,
    16
  ],
  "name" : "Endeavor"
}

首先,我们需要对枚举所有的编码健:

struct Beer : Codable {
   // ...
   
    enum CodingKeys: String, CodingKey {
        case name
        case brewery
        case abv
        case style
        case createdAt = "created_at"
        case bottleSizes = "bottle_sizes"
        case comments
    }
} 

接下来就是覆盖原有的 encode 方法:

extension Beer {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try container.encode(name, forKey: .name)
        try container.encode(abv, forKey: .abv)
        try container.encode(brewery, forKey: .brewery)
        try container.encode(style, forKey: .style)
        try container.encode(createdAt, forKey: .createdAt)
        try container.encode(comments, forKey: .comments)
        try container.encode(bottleSizes, forKey: .bottleSizes)
    }
}

最后,验证编码效果:

let beer = Beer.init(name: "name", brewery: "x", abv: "xx", style: BeerStyle.ipa, createdAt: Date.init(), bottleSizes: [2.3,3.6], comments: "xxx")
        
let encoder = JSONEncoder()
let data = try! encoder.encode(beer)
print(String(data: data, encoding: .utf8)!)

打印结果如下:

{    
    "comments":"xxx",
     "style":"ipa",
     "brewery":"x",
     "created_at":524716294.793119,
     "bottle_sizes": [2.3,3.6],
     "abv":"xx",
     "name":"name" 
}

其中编码过程中最重要的概念就是 container。在进行任何编码之前,我们都需要获取一个 container 对象,而该对象又有三种类型:

  1. Keyed Container:键值对字典类型

  2. Unkeyed Container:数值类型

  3. Single Value Container:仅仅输出 raw value

所以上面我们首先就创建了字典类型:

var container = encoder.container(keyedBy: CodingKeys.self)

然后,我们通过下面语句实现赋值:

try container.encode(value, forKey: .key)

另外,我们还可以获取 container 对象嵌套的 container 子对象。例如,我们可以对 bottle_sizes 中的数值进行四舍五入操作:

// 将 try container.encode(bottleSizes, forKey: .bottleSizes) 替换为:
var sizes = container.nestedUnkeyedContainer(
      forKey: .bottleSizes)

try bottleSizes.forEach {
      try sizes.encode($0.rounded())
}

// 结果就是: "bottle_sizes": [2.0,4.0]

自定义解码

与上面自定义编码类似,自定义解码也是通过覆盖默认方法实现。

extension Beer {
    init(from decoder: Decoder) throws {

    }
}

接下来,我们从 decoder 中获取 container 对象并将其赋值到对应属性上:

extension Beer {
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        name = try container.decode(String.self, forKey: .name)
        abv = try container.decode(String.self, forKey: .abv)
        brewery = try container.decode(String.self,
                                           forKey: .brewery)
        style = try container.decode(BeerStyle.self,
                                         forKey: .style)
        createdAt = try container.decode(Date.self,
                                             forKey: .createdAt)
        comments = try container.decodeIfPresent(String.self,
                                                     forKey: .comments)
        bottleSizes = try container.decode([Float].self, forKey: .bottleSizes)
    }
}

接下来,验证自定义的实现效果:

let jsonDic = ["comments":"xxx","style":"ipa","brewery":"x","created_at":524716294.793119,"bottle_sizes":[2.3,3.6],"abv":"xx","name":"name"] as [String : Any]
        
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
let decode = JSONDecoder()
do {
    let beer = try decode.decode(Beer.self, from: jsonData)
    print("解析成功:\(beer)")
} catch  {
    print("解析失败:\(error)")
}

打印结果如下:

解析成功:
Beer( name: "name",
         brewery: "x", 
         abv: "xx", 
         style: xxx.BeerStyle.ipa, 
         createdAt: 2017-08-18 02:31:34 +0000, 
         bottleSizes: [2.29999995, 3.5999999], 
         comments: Optional("xxx") )

当然,我们同样可以对嵌套的 bottleSizes 进行自定义:

init(from decoder: Decoder) throws {
    // ...

    var bottleSizesArray = try container.nestedUnkeyedContainer(forKey: .bottleSizes)
    var sizes: [Float] = []
        
    while (!bottleSizesArray.isAtEnd) {
        let size = try bottleSizesArray.decode(Float.self)
        sizes.append(size.rounded())
    }
    bottleSizes = Array.init(sizes)
}

扁平化对象

有时候,我们的 Model 可能与 JSON 数据的结构不一致。例如,假设 Beer 对象中 abvstyle 在 JSON 中是嵌套结构,但是我们不想在代码中新建嵌套结构。这时候,我们就可以使用自定义方法进行实现。

假设,JSON 对象形如:

{
   "name": "Lawnmower",
   "info": {
     "style": "kolsch",
     "abv": 4.9
   }
   // ...
}

要实现对象扁平化,首先我们需要定义出该嵌套结构的键值映射关系:

struct Beer : Codable {
  enum CodingKeys: String, CodingKey {
      case name
      case brewery
      case createdAt = "created_at"
      case bottleSizes = "bottle_sizes"
      case comments
      case info // <-- NEW
  }

  enum InfoCodingKeys: String, CodingKey {
      case abv
      case style
  }
}

在编码时候,我们使用 InfoCodingKeys 创建嵌套字典:

func encode(to encoder: Encoder) throws {
      var container = encoder.container(
          keyedBy: CodingKeys.self)

      var info = try encoder.nestedContainer(
          keyedBy: InfoCodingKeys.self)
      try info.encode(abv, forKey: .abv)
      try info.encode(style, forKey: .style)

    // ...
}

同样,在解码时取出其中的嵌套对象并进行赋值:

init(from decoder: Decoder) throws {
    let container = try decoder.container(
          keyedBy: CodingKeys.self)

    let info = try decoder.nestedContainer(
          keyedBy: InfoCodingKeys.self)
    abv = try info.decode(Float.self, forKey: .abv)
    style = try info.decode(BeerStyle.self,
          forKey: .style)

    // ...
}

对象继承

最后我们回到前面的问题,在 Swift 4 中进行类继承解析的时候到底发生了些什么。

首先,我们定义如下对象和继承关系:

class Person : Codable {
    var name: String?
    
    init() {}
    
    
}

class Employee : Person {
    var employeeID: String?
    
    override init() { super.init() }
}

接下来,我们分布检验 Employee 对象的编码和解码操作:

// 默认编码
let employee = Employee()
employee.employeeID = "emp123"
employee.name = "Joe"

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try! encoder.encode(employee)
print(String(data: data, encoding: .utf8)!)

// 默认解码
let jsonDic = ["employeeID":"emp123","name":"Joe"] as [String : Any]
        
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
let decode = JSONDecoder()
do {
    let employee = try decode.decode(Employee.self, from: jsonData)
    print("解析成功:\(employee)")
} catch  {
    print("解析失败:\(error)")
}

运行代码你会发现编码打印的结果为:

{
  "name" : "Joe"
}

同样的,解码操作也只有 name 属性被赋值了,employeeID 属性为 nil 。这显然与我们想要的理想结果相差甚远。所以,我们需要对上面的对象编码和解码方法进行自定义实现:

class Person : Codable {
    var name: String?

    private enum CodingKeys : String, CodingKey {
        case name
    }
    
    init() {}

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
    }
    
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
    }
}

class Employee : Person {
    var employeeID: String?

    private enum CodingKeys : String, CodingKey {
        case employeeID
    }
    
    override init() { super.init() }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        employeeID = try container.decode(String.self, forKey: .employeeID)
    }
    
    override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(employeeID, forKey: .employeeID)
    }
}

但是,如果你再次运行上面的测试代码的话会发现这次竟然是另一个极端。只有 employeeID 有值而继承得到的 name 属性则为 nil 。这是因为,上面子类在编解码过程中没有调用父类的方法。所以,我们需要将 Employee 中的方法修改为:

class Employee : Person {
    //...
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        
        try super.init(from: decoder)
        employeeID: = try container.decode(String.self, forKey: .employeeID:)
    }
    
    override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        
        try super.encode(to: encoder)
        try container.encode(employeeID, forKey: .employeeID)
    }
}

这样,我们就完美解决了之前的问题了。

另外,这里还有一个问题值得注意。上面进行父项编码操作的时直接使用了子类参数,而实际上我们可以使用更合适的参数进行编码操作:

// 替换  try super.encode(to: encoder)
try super.encode(to: container.superEncoder())

打印结果为:

{
  "super" : {
    "name" : "Joe"
  },
  "emp_id" : "emp123"
}

当然,我们可以对默认键 super 进行替换:

enum CodingKeys : String, CodingKey {
  case employeeID = "emp_id"
  case person
}

override func encode(to encoder: Encoder) throws {
   // ...
   try super.encode(to:
      container.superEncoder(forKey: .person))
}

修改后的打印结果为:

{
  "employeeID" : "emp123",
  "person" : {
    "name" : "Joe"
  }
}

当然,我们同样可以在解码时进行类似操作:

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    
     try super.init(from: container.superDecoder(forKey: .person))
    employeeID = try container.decode(String.self, forKey: .employeeID)
}

// 解码检测
let jsonDic = ["employeeID":"emp123","person":["name" : "Joe"] ] as [String : Any]
        
let jsonData = try! JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
let decode = JSONDecoder()
do {
    let employee = try decode.decode(Employee.self, from: jsonData)
    print("解析成功:\(employee)")
} catch  {
    print("解析失败:\(error)")
 }

总结

除了使用 Codable 的默认实现处理数据解析外,对于特殊情形我们完全可以通过自定义实现加以解决。虽然 Swift 还有一些地方有待完善,但是这不影响 Codable 功能的强大。希望未来 Swift 能给我们带来更多的惊喜,毕竟下个版本 ABI 就稳定了。

标签: Swift, 原创, JSON