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