我有一个问题JSON要从中的结构数组Swift3。我搜索了Stack Overflow,没有任何帮助(这里是屏幕截图)。我有一个struct这样的:
JSON
Swift3
Stack Overflow
struct
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 } }
以及该结构的数组:
private var productsArray = [ProductObject]()
当数组不为空时,然后我尝试在另一个类中打印它,它在调试器中显示:
[app.cartclass.ProductObject(prodID: "2", prodName: "produk 2", prodPrice: "IDR 1000000", imageURL: "someURL", qty: 1, stock: "11", weight: "200")]
数组无效JSON object。如何使其成为有效JSON对象?而且我想知道“ app.cartclass.ProductObject”这一部分是否有问题,以使其有效JSON object?
JSON object
编辑:
这是我序列化为的方法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"); }
如果要从自定义对象生成JSON,则首先需要将自定义对象转换为Dictionary,因此在ProductObject结构中创建一个如下所示的函数。
Dictionary
ProductObject
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 }
现在使用此函数从自定义对象数组生成字典数组ProductObject。
private var productsArray = [ProductObject]() let dicArray = productsArray.map { $0.convertToDictionary() }
这dicArray是由类型组成的[[String:Any]],现在您可以用来JSONSerialization从中生成JSON字符串dicArray。
dicArray
[[String:Any]]
JSONSerialization
if let data = try? JSONSerialization.data(withJSONObject: dicArray, options: .prettyPrinted) { let str = String(bytes: data, encoding: .utf8) print(str) }