c++编码风格指南
Codable
was introduced in Swift 4
which helps you convert your JSON to your model and model back to a JSON object. Codable
is a typalias of Decodable
and Encodable
protocols. Codable
is similar to Serialization in Java
Swift 4
中引入了Codable
,可帮助您将JSON转换为模型并将模型转换回JSON对象。 Codable
是一个typalias Decodable
和Encodable
协议。 Codable
类似于Java中的序列化
In this tutorial, we will only be covering
Encodable
in-depth在本教程中,我们将仅深入介绍
Encodable
可编码 (Encodable)
Encodable
is used for converting your data model to JSON object with the help ofJsonEncoder
Encodable
用于在JsonEncoder
的帮助下将数据模型转换为JSON对象
Let’s take a simple example of how to encode your data-model to the JSON object
让我们举一个简单的示例,说明如何将数据模型编码为JSON对象
- Create your data model and conform to Encodable 创建您的数据模型并符合Encodable
Create an instance of
JsonEncoder
and useencode(_:)
to encode thePhotoFeed
object to aJSON
object.创建
JsonEncoder
的实例,然后使用encode(_:)
将PhotoFeed
对象编码为JSON
对象。
Hurray! And just by writing a few lines of code, you have your data-model mapped to JSON.
万岁 ! 只需编写几行代码,您就可以将数据模型映射到JSON。
Encodable还可以做什么? (What else can Encodable do?)
可编码中的可选键 (Optional keys in Encodable)
JsonEncoder
will avoid adding keys to theJSON
object ONLY if the variables are optional and their respective values are nil
. In the below example, we have made feedDate
an optional variable and have set its value as nil. This will avoid adding the key to theJSON
object.
仅当变量是可选的并且它们各自的值为nil
JsonEncoder
才会避免将键添加到JSON
对象。 在下面的示例中,我们将feedDate
为可选变量,并将其值设置为nil。 这将避免将密钥添加到JSON
对象。
编码键 (CodingKey)
Let's say the server request needs the JSON keys
in snake_case
instead of camel_case
. This can be made possible with the help of CodingKey
.
假设服务器请求需要使用snake_case
而不是camel_case
的JSON keys
。 这可以通过CodingKey
。
CodingKey
tells the JSONEncoder
to map the variables present in the data-model
to the keys present in CodingKeys
. In the below example we have renamed the keys in enum CodingKeys from feedKey
→feed_key
, feedUrl
→ feed_url
and feedDate → feed_date
.
CodingKey
告诉JSONEncoder
存在于该变量映射data-model
到键呈现CodingKeys
。 在以下示例中,我们从feedKey
→ feed_key
, feedUrl
→ feed_url
和feedDate→ feed_date
重命名了枚举CodingKeys中的键。
处理嵌套数据 (Handle Nested Data)
Encoding nested data is as simple as encoding a simple data model. Let’s say the API server requests start asking you to send location
along with the feed. You can add the location in your data-model which will conform to Encodable
. You can add the new Location struct in your PhotoFeed
or as a new struct
outside the PhotoFeed.
编码嵌套数据就像编码简单数据模型一样简单。 假设API服务器请求开始要求您将location
和供稿一起发送。 您可以在符合Encodable
数据模型中添加位置。 您可以在添加新的定位结构PhotoFeed
或作为一个新的struct
的PhotoFeed之外。
自定义编码 (Customizing Encoding)
OutputFormatting (OutputFormatting)
This value tells the encoder to show how the encoded JSON object would be laid out; like the element order and its readability.
该值告诉编码器显示编码的JSON对象的布局方式。 如元素顺序及其可读性。
1. prettyPrinted
: It shows formatted JSON object with white space and indentation that makes it easy to read.
1. prettyPrinted
:显示带空格和缩进格式的JSON对象,使其易于阅读。
2. sortedKeys
: It shows formatted JSON that sorts keys in lexicographic order.
2. sortedKeys
:它显示格式化的JSON,按字典顺序对键进行排序。
编码策略 (Encoding Strategy)
Most of the time the server requests not always follow the camelCase
naming convention. There is a good chance that you may have a request that follows snake_case.
We can set the encoding strategy
that determines how data-model
variables are encoded in a JSON object. Let’s take an example:
大多数情况下,服务器请求并不总是遵循camelCase
命名约定。 您可能有一个跟随snake_case.
的请求snake_case.
我们可以设置encoding strategy
,该encoding strategy
确定如何在JSON对象中编码data-model
变量。 让我们举个例子:
1.useDefaultKeys
: It's a default strategy. It will use the same keys for encoding that have been mentioned in the data-model.
1. useDefaultKeys
:这是默认策略。 它将使用数据模型中提到的相同密钥进行编码。
2.convertFromSnake
: It will convert the camel-case🐫
variable from your data-model to snake-case🐍
while encoding the JSON object.
2. convertFromSnake
:它将在编码JSON对象时将camel-case🐫
变量从数据模型转换为snake-case🐍
。
3.custom
: You can have your custom implementation where you can choose the name of all the keys you have in the JSON object. This custom closure is called for each variable that is encoded.
3. custom
:您可以具有自定义实现,可以在其中选择JSON对象中所有键的名称。 对于每个已编码的变量,都会调用此自定义闭包。
We have taken an example where we prefix photo
to all the JSON encoded objects.
我们以一个示例为例,在photo
为所有JSON编码对象添加了前缀。
编码日期 (Encoding Dates)
JsonEncoder
supports encoding dates to the JSON object. Below are the list of strategies that you can use for encoding dates.
JsonEncoder
支持将日期编码到JSON对象。 以下是可用于编码日期的策略列表。
1.deferredToDate
: Number of seconds elapsed since 1st Jan 2001
represented in double
. An extremely rare chance you would be using this.
1. deferredToDate
:自1st Jan 2001
年1st Jan 2001
以来经过的秒数,以double
表示。 您将极少使用此功能。
2. iso8601
: This is the most widely used date-format. Use this link to understand more about date-format used under iso8601
2. iso8601
:这是使用最广泛的日期格式。 使用此链接可了解有关iso8601
下使用的日期格式的更多信息。
3. formatted(DateFormatter)
: You can add a custom DateFormatter
with the required dateFormat that you wish to encode your JSON object.
3. formatted(DateFormatter)
:您可以添加一个自定义的DateFormatter
,其中包含您希望对JSON对象进行编码的必需dateFormat。
4.custom((Date, Encoder) -> Void)
: This strategy helps you write custom code for parsing your dates to the encoded JSON object. Let’s take an example where you have to send multiple date formats in the JSON object.
4. custom((Date, Encoder) -> Void)
:此策略可帮助您编写用于将日期解析为已编码JSON对象的自定义代码。 让我们举个例子,您必须在JSON对象中发送多种日期格式。
5.millisecondsSince1970
: It encodes dates in milliseconds since midnight UTC on January 1, 1970
5. millisecondsSince1970
:自1970年1月1日午夜UTC起以毫秒为单位编码日期。
6.secondsSince1970
: It encodes dates in seconds since midnight UTC on January 1st, 1970
6. secondsSince1970
:它编码自1970年1月1日午夜UTC以来的秒数
编码原始数据 (Encoding Raw Data)
JsonEncoder
supports strategies for encoding your raw data into JSON objects. Here is a list of supported data encoding strategies
JsonEncoder
支持将原始数据编码为JSON对象的策略。 以下是受支持的数据编码策略的列表
1.base64
: encodes data using Base 64
1. base64
:使用Base 64编码数据
2.custom((Data, Encoder)
: encodes data using a custom function implemented by you.
2. custom((Data, Encoder)
:使用由您实现的自定义函数对数据进行编码。
By now you already got a gist of how the default custom encoding works and how would you use them. Still find it difficult to understand, comment below and I will add gist for you
到目前为止,您已经了解了默认自定义编码的工作原理以及如何使用它们。 仍然很难理解,请在下面评论,我将为您添加要点
编码特殊数字 (Encoding Exceptional Numbers)
This policy is used by a JsonEncoder
when it encounters exceptional floating-point values. Say if you have to update the server that some values are not-a-number NaN
and have infinite values that might need to be handled differently. Here is how you handle nan
, +veInfinity
and -veInfinity
当遇到异常的浮点值时, JsonEncoder
将使用此策略。 假设您必须更新服务器以使某些值不是数字NaN
且具有可能需要以不同方式处理的无限值。 这是处理nan
, +veInfinity
和-veInfinity
That’s pretty much you what you get in Encodable
🙌
这几乎就是您在Encodable
编码get中Encodable
东西
Did I miss a use-case? Let me know in the comments below!
我错过了用例吗? 在下面的评论中让我知道!
翻译自: https://medium.com/flawless-app-stories/complete-guide-to-codable-encodable-f15b408b8eaa
c++编码风格指南