Type Method

data(withJSONObject:options:)

Returns JSON data from a Foundation object.

Declaration

class func data(withJSONObject obj: Any, options opt: JSONSerialization.WritingOptions = []) throws -> Data

Parameters

obj

The object from which to generate JSON data. Must not be nil.

options

Options for creating the JSON data.

See JSONSerialization.WritingOptions for possible values.

Return Value

JSON data for obj, or nil if an internal error occurs. The resulting data is encoded in UTF-8.

Discussion

If obj will not produce valid JSON, an exception is thrown. This exception is thrown prior to parsing and represents a programming error, not an internal error. You should check whether the input will produce valid JSON before calling this method by using isValidJSONObject(_:).

Setting the prettyPrinted option will generate JSON with whitespace designed to make the output more readable. If that option is not set, the most compact possible JSON will be generated.

See Also

Creating JSON Data

class func isValidJSONObject(Any)

Returns a Boolean value that indicates whether a given object can be converted to JSON data.