如何从 Swift 3 中的结构数组生成 JSON? [英] How to Make JSON from Array of Struct in Swift 3?

查看:36
本文介绍了如何从 Swift 3 中的结构数组生成 JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在从 Swift3 中的结构数组生成 JSON 时遇到问题.我在 Stack Overflow 中搜索,没有任何帮助(这里是 screenshot).我有一个像这样的 struct:

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

和那个结构体的数组:

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")]

该数组不是有效的 JSON 对象.如何使它成为有效的 JSON 对象?我想知道app.cartclass.ProductObject"这部分是否有问题,使其成为有效的 JSON 对象?

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?

这是我如何序列化为 JSON:

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

推荐答案

如果您想从自定义对象生成 JSON,那么首先您需要将自定义对象转换为 Dictionary,因此创建一个函数,例如下面在您的 ProductObject 结构中.

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
}

现在使用这个函数从自定义对象数组ProductObject生成字典数组.

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

这里dicArray[[String:Any]]类型组成,现在可以使用JSONSerialization生成JSON 来自这个 dicArray 的字符串.

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

这篇关于如何从 Swift 3 中的结构数组生成 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆