SWIFT4 JSON parsing

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.