In other words, SWIFT4 provides two classes (Jsonencoder, Jsondecoder) for JSON serialization and deserialization,
Under the test, you can convert a custom object (allowing multiple layers of nesting) to JSON data and reverse parse into model
But it's a lot of trouble to write a long string of code each time, here we use Swift's features, protocols, and protocol extensions to enable fast model and JSON interoperability.
Create a swift FILE
////Json.swift//Swiftjson////Created by Crazy where on 2017/6/18.//Copyright 2017 Facishare. All rights reserved.//Import Foundationtypealias jsoncodable= decodable &encodableprotocol jsonparser:jsoncodable {func tojsondata ()Data?StaticFunc Modelwithjsondata (data:data), any?func tojsonstring ()String?StaticFunc modelwithjsonstring (string: String), any?}extension jsonparser{func tojsondata ()Data? { return Try?Jsonencoder (). Encode (self)}StaticFunc Modelwithjsondata (data:data), any?{ return Try?Jsondecoder (). Decode (Self.self, From:data)} func tojsonstring ()String?{ returnString.init (Data:self.toJSONData ()!, Encoding:String.Encoding.utf8)} StaticFunc modelwithjsonstring (string: String), any?{ returnSelf.modelwithjsondata (data:string. Data (using: String.Encoding.utf8)!) }}
Write the upper part of the code, and then the custom class implements the Jsonparser protocol to implement the default JSON and model conversions
SWIFT4 JSON parsing