Alex Andrews
Alex Andrews

Reputation: 1498

Is there anyway JSON(node: ) can be called with [String: Any] type in Vapor

I have a method, which will return a [String: Any] dictionary as below,

  func getDetailDictionary() -> [String: Any] {
    // demo code
    let followers = [1, 2, 3, 4, 5]
    return [
      "name": "sample name",
      "followers": followers
    ]
  }

I need to convert this object to JSON, so that I can send it back to the client as a ResponseRepresentable object.

I used the following to prepare the JSON object:

let jsonData = try JSON(node: getDetailDictionary())

But this giving error, telling this doesn't match any available overloads. I don't think [String:Any] type is not handled in JSON(node: ) method implementation. Is there any way we can get this issue resolved in Vapor?

Upvotes: 1

Views: 287

Answers (1)

Caleb Kleveter
Caleb Kleveter

Reputation: 11494

I was able to get this code working by assigning the type of all the values to Node. This might not be what you want if you want to interact with the data in the dictionary before returning it, but I think it will work.

func getDetailDictionary() -> Node {
    // demo code
    let followers: Node = [1, 2, 3, 4, 5]
    let dict: Node = [
        "name": "sample name",
        "followers": followers
    ]
    return dict
}

drop.get("test") { req in
    return JSON(getDetailDictionary())
}

Upvotes: 2

Related Questions