具有更快的 json 响应 [英] With swifter json response

查看:28
本文介绍了具有更快的 json 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swifter 库用 swift 创建简单的 rest api
我如何响应 json 数据?

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))
}

但是有下面的错误信息

序列化错误:invalidObject

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)
              })
...

所以,我需要通过 guard JSONSerialization.isValidJSONObject(object) else {

另外,图书馆没有足够的文件,我该如何解决这个问题?

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

推荐答案

使用 codable 和一个 jsonEncoderusers 数组转换为数据然后将它们转换回 jsonObject 并传入:

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)"))
}

请注意,您应该考虑向服务调用方返回错误.我用过 .internalServerError 但你可以考虑返回一个更好的错误.

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.

这篇关于具有更快的 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆