Ask Your Question
1

What are the methods for converting Swift objects to JSON format?

asked 2023-03-31 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-09-12 02:00:00 +0000

bukephalos gravatar image

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}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-03-31 11:00:00 +0000

Seen: 10 times

Last updated: Sep 12 '22