如何在Swift 3中从Struct数组制作JSON? [英] How to Make JSON from Array of Struct in Swift 3?

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

问题描述

我在从Swift3中的结构数组制作JSON时遇到问题.我在Stack Overflow中搜索,没有任何帮助(在这里屏幕截图).我有这样的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 object.如何使其成为有效的JSON对象?而且我想知道"app.cartclass.ProductObject"这一部分是否有问题,以使其不能成为有效的JSON object?

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,因此请在结构.

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从此dicArray生成JSON字符串.

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中从Struct数组制作JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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