Skip to content

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 OutputFormatting
    The 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

Instance Methods

Enumerations

Relationships

Conforms To