How to assign elements of a dictionary to JSON obj

2019-08-03 15:19发布

In Vapor 1.5 I used to assign the elements of an existing dictionary to a JSON object as shown below. How can I do this 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

标签: swift vapor
1条回答
Lonely孤独者°
2楼-- · 2019-08-03 16:01

This is basically, JSON serialization in swift. Decoding the JSON object to a Dictionary and then modifying the dictionary and creating a new 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"
    }
}

I strongly recommend to create struct or class for your data type. It would be much safer in casting using the codable protocol and much easier to convert between JSON and your objects type because of the content protocol in vapor version 3.

查看更多
登录 后发表回答