How to create JSON object in Swift

In this Swift programming tutorial, you will be learning how to create JSON objects. Here I am going to show you two different ways that can perform the task.

To create a JSON object in Swift, you can use the JSONSerialization class to convert a dictionary or array to a JSON object. This is an object that is able to convert between JSON and the equivalent Foundation objects.

Here is an example given below:

let dictionary: [String: Any] = ["key": "value"]

// convert the dictionary to JSON data
let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: [])

// convert the JSON data to a JSON object
let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])

Alternative method

Now let’s look at an alternative method that can also perform this task.

You can use the Swift Codable protocol to convert an object to a JSON object. In the program given below, you can see how to do it:

struct MyObject: Codable {
    var key: String
}

let object = MyObject(key: "value")

// encode the object to JSON data
let encoder = JSONEncoder()
let jsonData = try encoder.encode(object)

// decode the JSON data to a JSON object
let decoder = JSONDecoder()
let jsonObject = try decoder.decode(MyObject.self, from: jsonData)

That’s it.

We have don the task in two different methods. Please let us know which one you prefer in the comment below.

Also read: Parsing a JSON Array in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *