Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are two methods for converting Swift objects to JSON format:

  1. Using Codable protocol:

Swift 4 introduced a Codable protocol that provides a convenient way to decode (deserialize) and encode (serialize) data types to and from JSON. To use Codable, you need to define a struct or class that conforms to it, and then use an instance of JSONDecoder or JSONEncoder to convert between the Swift object and JSON format.

For example, to encode a custom struct to JSON format:

struct Person: Codable {
  var name: String
  var age: Int
}

let person = Person(name: "John", age: 30)
let encoder = JSONEncoder()
do {
    let jsonData = try encoder.encode(person)
    let jsonString = String(data: jsonData, encoding: .utf8)
    print(jsonString)
} catch {
    print(error.localizedDescription)
}

Output:

{"name":"John","age":30}
  1. Using SwiftyJSON:

SwiftyJSON is a third-party library that provides a simple way to parse JSON data in Swift. It supports object mapping, error handling, and chaining syntax.

To use SwiftyJSON, you need to include it in your project using CocoaPods or Swift Package Manager, and then use its JSON() method to convert between the Swift object and JSON format.

For example, to encode a custom struct to JSON format:

import SwiftyJSON

struct Person {
  var name: String
  var age: Int

  func toJSON() -> JSON {
    return JSON(["name": name, "age": age])
  }
}

let person = Person(name: "John", age: 30)
let jsonString = person.toJSON().rawString()
print(jsonString)

Output:

{"name":"John","age":30}