JSONEncoder
An object that encodes instances of a data type as JSON objects.
Declaration
class JSONEncoderMentioned in
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.
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
First Steps
Customizing Encoding
outputFormattingJSONEncoder.OutputFormattingkeyEncodingStrategyJSONEncoder.KeyEncodingStrategyuserInfo