I was recently using JSONEncoder.encode()
(and its counterpart, JSONDecoder.decode()
), which is marked in the documentation as throws
. Unfortunately, the documentation does not go into detail on when/how/what this method could throw. Does anybody have any insight in this? I'm asking because I am wondering if an error here is common enough to implement a user-facing error handling for this.
thanks
An object that encodes instances of a data type as JSON objects. iOS 7.0+ iPadOS 7.0+ macOS 10.9+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Xcode 9.0+
Remember, Swift's String , Int , and Bool are all Codable ! Earlier I wrote that your structs, enums, and classes can conform to Codable . Swift can generate the code needed to extract data to populate a struct's properties from JSON data as long as all properties conform to Codable .
JSONEncoder is an object that encodes instances of a data type as JSON objects. JSONEncoder supports the Codable object. print("JSON String : " + jsonString!) JSONEncoder will give us the JSON data which is used to retrieve JSON string.
// JSONEncoder.swift open func encode<T : Encodable>(_ value: T) throws -> Data { let encoder = _JSONEncoder(options: self.options) The encode () method takes some Encodable value and returns the raw JSON Data. The actual encoding work is in the private class _JSONEncoder.
The encode() method takes some Encodable value and returns the raw JSON Data. The actual encoding work is in the private class _JSONEncoder. This approach keeps JSONEncoder as the type with the friendly public interface, and _JSONEncoder as the fileprivate (everyone’s favorite!) class that implements the Encoder protocol.
JSON contains some associated values and Swift can’t synthesise the Codable implementation for us. The implementation is pretty straightforward, and the code looks like this: When it comes to the encoding part, we know in advance the type we want to insert in the encoder’s container.
The big idea is if individual instances such as strings and numbers can be encoded and decoded, then you can archive and unarchive entire object graphs. In the Swift standard library, there are things that are encodable as well as encoders. Encodable is a protocol. A conforming type can encode itself to some other representation.
JSONEncoder.encode()
throws EncodingError.invalidValue
when one of the values you are about to encode is not valid (e.g. Double.infinity
if the NonConformingFloatEncodingStrategy
is set to the default .throw
, since JSON does not natively support infinity as a number).
You can see this in the source, and read more about the error in the EncodingError
documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With