如何在Vapor 3中将字典的元素分配给JSON对象?

时间:2018-07-07 11:50:14

标签: swift vapor

在Vapor 1.5中,我曾经将现有字典的元素分配给JSON对象,如下所示。我该怎么做Vapor 3?

 func makeCustomJSON(jsonFromReading: JSON, clientData: DataFromClient) throws -> JSON{

    var dictionaryOfStrings = [String:String]()

    dictionaryOfStrings["ChangesMadeBy"] = "Cleaner"
    dictionaryOfStrings["BookingNumber"] = clientData.bookingNumber
    dictionaryOfStrings["Claimed"] = "false"
     //some 50 properties more...


    //object read from /Users
    var finalJsonObj = jsonFromReading

    //assign the values of dictionaryOfStrings to finalJsonObj
    for i in dictionaryOfStrings {
        let key  = i.key
        let value = i.value
        finalJsonObj[key] = try JSON(node:value)
    }

    //make json from object under CancelledBy and assign it to arrayOfTimeStampObjs
    var arrayOfTimeStampObjs = try jsonFromReading["CancelledBy"]?.makeJSON() ?? JSON(node:[String:Node]())


    //assign dictionaryOfStrings to current time stamp when booking is claimed
    arrayOfTimeStampObjs[clientData.timeStampBookingCancelledByCleaner] = try JSON(node:dictionaryOfStrings)
    finalJsonObj["CancelledBy"] = arrayOfTimeStampObjs

    return finalJsonObj

} //end of makeCustomJSON

1 个答案:

答案 0 :(得分:2)

这基本上是迅速进行JSON序列化。将JSON对象解码为Dictionary,然后修改字典并创建新的JSON。

router.get("test") { req -> String in

    let jsonDic = ["name":"Alan"]
    let data = try JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
    let jsonString = String(data: data, encoding: .utf8)
    return jsonString ?? "FAILED"
}

router.get("test2") { req -> String in
    do {
        // Loading existing JSON
        guard let url = URL(string: "http://localhost:8080/test") else {
            return "Invalid URL"
        }

        let jsonData = try Data(contentsOf: url)
        guard var jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String:String] else {
            return "JSONSerialization Failed"
        }

        // Apply Changes
        jsonDic["name"] = "John"

        // Creating new JSON object
        let data = try JSONSerialization.data(withJSONObject: jsonDic, options: .prettyPrinted)
        let jsonString = String(data: data, encoding: .utf8)
        return jsonString ?? "FAILED"
    }catch{
        return "ERROR"
    }
}

我强烈建议为您的数据类型创建结构或类。由于蒸气版本3中的codable协议,使用content协议进行转换会更安全,并且在JSON和对象类型之间进行转换会更容易。