Class
JSONEncoder
iOS 8.0+
iPadOS 8.0+
Mac Catalyst 8.0+
macOS 10.10+
tvOS 9.0+
watchOS 2.0+
An object that encodes instances of a data type as JSON objects.
class JSONEncoder
Overview
The example below shows how to encode an instance of a simple GroceryProduct type from a JSON object. The type adopts doc://com.apple.documentation/documentation/swift/codable so that it’s encodable as JSON using a JSONEncoder instance.
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."
}
*/
Topics
Structures
struct OutputFormattingThe output formatting options that determine the readability, size, and element order of an encoded JSON object.
Initializers
init()Creates a new, reusable JSON encoder with the default formatting settings and encoding strategies.
Instance Properties
var dataEncodingStrategy: JSONEncoder.DataEncodingStrategyThe strategy that an encoder uses to encode raw data.var dateEncodingStrategy: JSONEncoder.DateEncodingStrategyThe strategy used when encoding dates as part of a JSON object.var keyEncodingStrategy: JSONEncoder.KeyEncodingStrategyA value that determines how to encode a type’s coding keys as JSON keys.var nonConformingFloatEncodingStrategy: JSONEncoder.NonConformingFloatEncodingStrategyThe strategy used by an encoder when it encounters exceptional floating-point values.var outputFormatting: JSONEncoder.OutputFormattingA value that determines the readability, size, and element order of the encoded JSON object.var userInfo: [CodingUserInfoKey : any Sendable]A dictionary you use to customize the encoding process by providing contextual information.
Instance Methods
func encode<T>(T) throws -> DataReturns a JSON-encoded representation of the value you supply.func encode(_:configuration:)
Enumerations
enum DataEncodingStrategyThe strategies for encoding raw data.enum DateEncodingStrategyThe formatting strategies available for formatting dates when encoding a date as JSON.enum KeyEncodingStrategyThe values that determine how to encode a type’s coding keys as JSON keys.enum NonConformingFloatEncodingStrategyThe strategies for encoding nonconforming floating-point numbers, also known as IEEE 754 exceptional values.
Relationships
Conforms To
ContentEncoderJWTJSONEncoderSwift.CopyableSwift.EscapableSwift.SendableSwift.SendableMetatype