Search code examples
swiftswift5swifter

With swifter json response


I am create simple rest api with swift using swifter library
How i can response json data?

import Swifter

let server = HttpServer()
server["/hello"] = { request in
    var userList:[Any] = []
    for user in users {
        var b : [String: Any] = [:]
        b["name"] = user.name
        b["id"] = user.id
        userList.append(b)
    }
    return .ok(.json(userList))
}

But there is below error message

Serialization error: invalidObject


I check the library source code, and found the error message reason

...
//Library Source code
    func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
        do {
            switch self {
            case .json(let object):
              guard JSONSerialization.isValidJSONObject(object) else {
                throw SerializationError.invalidObject
              }
              let data = try JSONSerialization.data(withJSONObject: object)
              return (data.count, {
                try $0.write(data)
              })
...

So, I need pass guard JSONSerialization.isValidJSONObject(object) else {


also, there is no enough document for the library, How I can fix this problem ?


Solution

  • Use codable and a jsonEncoder to convert the users array to data and then convert them back to a jsonObject and pass it in:

    do {
        let jsonEncoder = JSONEncoder()
        let jsonData = try jsonEncoder.encode(users)
    
        let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
        return .ok(.json(jsonObject))
    } catch {
        print(error)
        return .internalServerError(.htmlBody("\(error.localizedDescription)"))
    }
    

    Note that you should consider returning an error to the caller of the service. I've used .internalServerError but you may consider returning a better error.