gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 07:01:09 26 4
gpt4 key购买 nike

在 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

最佳答案

基本上,这就是 swift 中的 JSON 序列化。将 JSON 对象解码为字典,然后修改字典并创建新的 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"
}
}

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

关于swift - 如何将字典的元素分配给 Vapor 3 中的 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51222934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com