我该如何在Swift 3中将包含自定义类的数组转换为JSON?

3

我需要在Swift 3中创建以下JSON,并且不想使用外部库。我尝试了这个答案,但是我在数组内使用了自定义类(store和product),所以它无法正常工作。

"order": 
    [{
        "store": 1,
        "product": [ 
        {
            "id": 1,
            "quantity": 1 
        },
        {
            "id": 2,
            "quantity": 5 
        }]
    },
    {
        "store": 4, 
        "product": [ {
            "id": 1,
            "quantity": 1 
        },
        {
            "id": 3,
            "quantity": 1 
        }]
    }]
}

可能是如何在Swift 3中从结构体数组创建JSON?的重复问题。 - Nirav D
2个回答

3

我相信你可以通过以下方式实现:

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) 点击您发布的示例链接

NSJSONSerialization.dataWithJSONObject(order.toJSON(), options: nil, error: nil)

如果我想要一个产品数组,该怎么办?现在它只添加了一个产品和一个商店。 - Marchu
你可以用几种不同的方式做到这一点。你可以在Order.toJSON()函数中循环遍历产品数组,并将每个产品添加到字典中。请查看我对Order对象的编辑作为示例。但是,根据您想要如何在JSON对象中存储产品,可能需要进行一些重构。 - sargturner
@Marchu 如果我还能做更多来使这个答案更可接受,请告诉我。如果这个答案满足了您的需求,请标记为正确。谢谢! - sargturner

0
在你的类中添加一个名为"ToDictionary"的方法,该方法返回一个手动编码的包含你的字段和值的字典。然后只需对该字典调用NSJSONSerialization即可。在ObjC下,你可以使用反射,但这还没有实现...

请参考以下内容了解反射 - https://appventure.me/2015/10/24/swift-reflection-api-what-you-can-do/ - Santosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接