JSONEncoder.encode(_:) should specify the encoding of the resulting data

Number:rdar://FB7699234 Date Originated:12 May 2020
Status:Open Resolved:
Product:Documentation Product Version:
Classification: Reproducible:
While Foundation's JSONSerialization.data(withJSONObject:) *does* specify that the resulting data is encoded in UTF-8, JSONEncoder.encode(_:) *does not*.

This is problematic because it means the following code sample from the JSONEncoder page (https://developer.apple.com/documentation/foundation/jsonencoder) and several third-party Codable tutorials is not necessarily correct:

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

Relying on the JSON spec alone, the data could be UTF-8, UTF-16, or UTF-32.

In practice, JSONEncoder appears to be implemented using JSONSerialization (on Darwin and Linux) and people rely on this, so I wouldn't expect the encoding of the returned data to change any time soon. It would still be nice if JSONEncoder's returned data encoding was documented though.


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!