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

2019-01-15 11:30发布

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). I have a struct like this:

public struct ProductObject {
    var prodID: String
    var prodName: String
    var prodPrice: String
    var imageURL: String
    var qty: Int
    var stock: String
    var weight: String

    init(prodID: String, prodName: String, prodPrice: String, imageURL: String, qty: Int, stock: String, weight: String){
        self.prodID = prodID
        self.prodName = prodName
        self.prodPrice = prodPrice
        self.imageURL = imageURL
        self.qty = qty
        self.stock = stock
        self.weight = weight
    }
}

and the array of that struct:

private var productsArray = [ProductObject]()

When the array is not empty, and then I tried to print it in another class, it shows this in debugger:

[app.cartclass.ProductObject(prodID: "2", prodName: "produk 2", prodPrice: "IDR 1000000", imageURL: "someURL", qty: 1, stock: "11", weight: "200")]

The array is not a valid JSON object. How to make it a valid JSON object? And I wonder whether this part "app.cartclass.ProductObject" is a problem or not to make it a valid JSON object?

edit:

Here's how I serialize into a JSON:

var products = [String:Any]()
    for j in 0 ..< cart.numberOfItemsInCart()  {
        products=["\(j)":cart.getAllProduct(atIndex: j)]
    }
    if let valid = JSONSerialization.isValidJSONObject(products) {
        do {
            let jsonproducts = try JSONSerialization.data(withJSONObject: products, options: .prettyPrinted) as! [String:Any]
            //print(jsonproducts)
        } catch let error as NSError {
            print(error)
        }
     } else {
         print("it is not a valid JSON object");
     }

1条回答
Ridiculous、
2楼-- · 2019-01-15 12:08

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)
}
查看更多
登录 后发表回答