如何将struct转换为json Swift

时间:2016-08-11 20:46:40

标签: ios swift

我需要像这样创建JSON,但我的代码不起作用:

{
    "room": "string",
    "products": [{
        "name": "string",
        "quantity": 0
    }],
    "observations": "string",
    "date": "dd-mm-yyyy hh:mm:ss"
}

我需要将此结构转换为JSON,我的代码是:


struct Products: JSONSerializable {
    let name: String
    let quantity: Int   
}
struct Pedido: JSONSerializable{
    let room: String
    let products: Array
    let observations: String
    let date: NSDate
}

此代码无效,在日志中返回nil:


 let JSONPedido = Pedido(room: receivedString,
                         products: products,
                         observations: observationString!,
                         date: date).ToJSON()

1 个答案:

答案 0 :(得分:0)

使用结构体,您还可以创建一个变量,该变量将充当结构值的字典表示形式。在这种情况下,它看起来像这样:

struct Pedido {
    let room: String
    let products: Array
    let observations: String
    let date: NSDate
    var pedidoJSON: [String: AnyObject] {
        return ["room" : room, "products": products, "observations": observations, "date": date]
    }
}

然后当您需要JSON值时,您可以像这样访问它。

//assuming you already have a pedido instance
let pedidoJson = pedidoInstance.pedidoJSON