可编码对象到JSON转换的问题

可编码对象到JSON转换的问题,json,swift,mongodb,Json,Swift,Mongodb,抱歉,如果这是一个基本问题,我在Swift中使用API和JSON是新手。我试图提交post请求,但收到: 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因是:“JSON写入中的类型无效(\uu SwiftValue)” 我相信这是由于一个不正确的/不可转换的类型,但我尝试了我传递的变量的多种不同排列,它继续失败 这是我的ContentView: struct ContentView:View{ @州var town:Space=Space(标题:“测试

抱歉,如果这是一个基本问题,我在Swift中使用API和JSON是新手。我试图提交post请求,但收到:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因是:“JSON写入中的类型无效(\uu SwiftValue)”

我相信这是由于一个不正确的/不可转换的类型,但我尝试了我传递的变量的多种不同排列,它继续失败

这是我的
ContentView

struct ContentView:View{
@州var town:Space=Space(标题:“测试城市”,描述:“这是否有效”)
var body:一些观点{
按钮(操作:{
中的Api.postRequest(参数:[“space”:town],urlString:Api.spacepostrl){(更新)
打印(“\(更新)”)
}
}) {
文本(“请求后”)
}
}
}
基础数据
struct

结构空间:可编码{
变量标题:字符串
变量说明:字符串
}
以及我尝试的API调用:

类Api{
静态let spacepostrl=”http://localhost:3001/spaces"
静态let spaceGetUrl=”http://localhost:3001/"
静态func postRequest(参数:[String:Codable],urlString:String,完成:@escaping(Int)->()){
guard let url=url(字符串:urlString)else{return}
let body=try?JSONSerialization.data(带jsonObject:param)
var-request=URLRequest(url:url)
request.httpBody=body
request.httpMethod=“POST”
URLSession.shared.dataTask(with:request){(data,request,error)在
guard let update=data else{return}
做{
让update=尝试JSONDecoder().decode(Int.self,from:update)
DispatchQueue.main.async{
完成(更新)
}
}
抓住{
打印(错误)
}
}
}
}

我试过了,但它仍然抛出了相同的错误(我认为在我的JSONSerialization中,在线程1中报告)。JSONDecoder不只是为了处理服务器如何响应我的post请求吗?你能发布请求的原始json响应吗?我相信服务器会使用[status:200]的[String:Int]字典进行响应,如果需要,我可以尝试获取实际的json(预测[String:Int]时仍然会出现相同的错误)您需要根据json更新您的模型。
class Api {
     static let spacePostUrl = "http://localhost:3001/spaces"
     static let spaceGetUrl = "http://localhost:3001/"

     static func postRequest(param: [String : Codable], urlString: String, completion: @escaping (Int) -> ()) {
    guard let url = URL(string: urlString) else { return }
    
    let body = try? JSONSerialization.data(withJSONObject: param)
    
    var request = URLRequest(url: url)

    request.httpBody = body
    request.httpMethod = "POST"
    
    let task = URLSession.shared.dataTask(with: request) { (data, request, error) in
        guard let update = data else { return }
        do {
            let update = try JSONDecoder().decode(Space.self, from: update)
            DispatchQueue.main.async {
                completion(update)
            }
        }
        catch {
            print(error)
        }
    }
   task.resume()
  }
}