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)
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)
}