gpt4 book ai didi

json - 来自 `[String: Any]` 字典的 Vapor JSON

转载 作者:搜寻专家 更新时间:2023-10-31 22:28:55 24 4
gpt4 key购买 nike

如果我构建一个 Swift 字典,即 [String: Any] 我如何将其作为 JSON 返回?我试过了,但它给了我错误:Argument labels '(node:)' do not match any available overloads

drop.get("test") { request in
var data: [String: Any] = [:]

data["name"] = "David"
data["state"] = "CA"

return try JSON(node: data)
}

最佳答案

非常复杂,但这允许您使用 [String:Any].makeNode(),只要内部是 NodeRepresentable、NSNumber based 或 NSNull :) --

import Node

enum NodeConversionError : LocalizedError {
case invalidValue(String,Any)
var errorDescription: String? {
switch self {
case .invalidValue(let key, let value): return "Value for \(key) is not NodeRepresentable - " + String(describing: type(of: value))
}
}
}

extension NSNumber : NodeRepresentable {
public func makeNode(context: Context = EmptyNode) throws -> Node {
return Node.number(.double(Double(self)))
}
}

extension NSString : NodeRepresentable {
public func makeNode(context: Context = EmptyNode) throws -> Node {
return Node.string(String(self))
}
}

extension KeyAccessible where Key == String, Value == Any {
public func makeNode(context: Context = EmptyNode) throws -> Node {
var mutable: [String : Node] = [:]
try allItems.forEach { key, value in
if let _ = value as? NSNull {
mutable[key] = Node.null
} else {
guard let nodeable = value as? NodeRepresentable else { throw NodeConversionError.invalidValue(key, value) }
mutable[key] = try nodeable.makeNode()
}
}
return .object(mutable)
}

public func converted<T: NodeInitializable>(to type: T.Type = T.self) throws -> T {
return try makeNode().converted()
}
}

使用该 header ,您可以:

return try JSON(node: data.makeNode())

关于json - 来自 `[String: Any]` 字典的 Vapor JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884674/

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