JSONEncoder

An object that encodes instances of a data type as JSON objects.
将一个数据(泛指)类型的实例编码为JSON对象的对象。

Overview

Overview

The example below shows how to encode an instance of a simple GroceryProduct type from a JSON object. The type adopts Codable so that it's encodable as JSON using a JSONEncoder instance.

下面的示例显示如何从JSON对象编码简单GroceryProduct类型的实例。 该类型采用Codable,因此可以使用JSONEncoder实例将其编码为JSON。

struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}

let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)

/* Prints:
 {
   "name" : "Pear",
   "points" : 250,
   "description" : "A ripe pear."
 }
*/
  /// Encodes the given top-level value and returns its JSON representation.
  /// 对给定的顶级值进行编码并返回其JSON表示。
    ///
    /// - parameter value: The value to encode. 要编码的值。
    /// - returns: A new `Data` value containing the encoded JSON data. 包含编码的JSON数据的新“Data”值。
    /// - throws: `EncodingError.invalidValue` if a non-conforming floating-point value is encountered during encoding, and the encoding strategy is `.throw`.
    /// 如果在编码期间遇到不符合的浮点值,
    /// 则为“EncodingError.invalidValue”,编码策略为“.throw”。
    /// - throws: An error if any value throws an error during encoding.
    open func encode(_ value: T) throws -> Data where T : Encodable
image.png

从上面示例看到我们传递的参数类型为遵循了Encodable 协议的类型T,

你可能感兴趣的:(JSONEncoder)