あなたは、リフレクションを使用することができますが、それはまだここではないです:
1)あなたのオブジェクトのクラスではtoJSON()関数を作成し
2 )プロパティとその値を格納する辞書をこのオブジェクトに作成します。ここで
は、あなたのJSONの例をオフに基づいて、少人数のクラスのカップルの例です:
class Order {
var store: Store!
var products: [Product]!
init(store: Store, products: [Product]) {
self.store = store
self.products = products
}
func toJSON() -> [String : Any] {
var dictionary: [String : Any] = [:]
dictionary["store"] = store.toJSON()
var productsDictionary: [Int : Any] = [:]
for index in 0...self.products.count - 1 {
let product: Product = products[index]
productsDictionary[index] = product.toJSON()
}
dictionary["product"] = productsDictionary
return dictionary
}
}
class Store {
var id: Int!
init(id: Int) {
self.id = id
}
func toJSON() -> [String:Any] {
var dictionary: [String : Any] = [:]
dictionary["id"] = self.id
return dictionary
}
}
class Product {
var id: Int!
var quantity: Int!
init(id: Int, quantity: Int) {
self.id = id
self.quantity = quantity
}
func toJSON() -> [String:Any] {
var dictionary: [String : Any] = [:]
dictionary["id"] = self.id
dictionary["quantity"] = self.quantity
return dictionary
}
}
3)あなたは配列からJSONを作るために[方法の
NSJSONSerialization.dataWithJSONObject(order.toJSON(), options: nil, error: nil)
可能な複製を掲載例のリンクをクリックしてくださいSwift 3の構造の?](http://stackoverflow.com/questions/40989483/how-to-make-json-from-array-of-struct-in-swift-3) –