How to Make JSON from Array of Struct in Swift 3?

后端 未结 1 594
执念已碎
执念已碎 2020-12-06 15:27

I have a problem to make a JSON from an array of struct in Swift3. I searched in Stack Overflow, nothing help me (here the screenshot)

相关标签:
1条回答
  • 2020-12-06 15:48

    If you want to make JSON from custom object then first you need to convert your custom object to Dictionary, so make one function like below in your ProductObject struct.

    func convertToDictionary() -> [String : Any] {
        let dic: [String: Any] = ["prodID":self.prodID, "prodName":self.prodName, "prodPrice":self.prodPrice, "imageURL":self.imageURL, "qty":qty, "stock":stock, "weight":weight]
        return dic
    }
    

    Now use this function to generate Array of dictionary from Array of custom object ProductObject.

    private var productsArray = [ProductObject]()
    let dicArray = productsArray.map { $0.convertToDictionary() }
    

    Here dicArray is made of type [[String:Any]], now you can use JSONSerialization to generate JSON string from this dicArray.

    if let data = try? JSONSerialization.data(withJSONObject: dicArray, options: .prettyPrinted) {
        let str = String(bytes: data, encoding: .utf8)
        print(str)
    }
    
    0 讨论(0)
提交回复
热议问题