2

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");
     }
5
  • why dont you wana use class in place of struct ? Commented Dec 6, 2016 at 7:02
  • @ShobhakarTiwari because in class cartclass there are a lot of other things to do Commented Dec 6, 2016 at 7:07
  • then use nsjsonserialization to convert it into json data Commented Dec 6, 2016 at 7:10
  • @ShobhakarTiwari as I stated above, it's not a valid JSON object, that's why I ask for help to change it into a valid one. It throws an error. Commented Dec 6, 2016 at 7:13
  • how you converting it , where is that code ? Commented Dec 6, 2016 at 7:14

1 Answer 1

14

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

It's working! So, that my way of translating into Dictionary is wrong. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.