【问题标题】:Syntax of JSON - Body Post request - SWIFT4JSON 的语法 - 正文发布请求 - SWIFT4
【发布时间】:2019-06-18 12:00:20
【问题描述】:

我正在尝试使用来自服务器的 HTTP Post 请求获取 JSON,但我认为我的请求正文是错误的。我尝试了一切,但找不到解决方案。应用程序崩溃了。

我在请求的主体(newTodo 变量)上尝试了一些不同的语法,例如:

'{"api_key":"mykey123","api_secret":"asdfg","uniqueid":"csd23cdse34ww","password":"secret123","pin":"12345"}'

["api_key": "mykey123", "api_secret": "asdfg","uniqueid": "csd23cdse34ww","password": "secret123","pin": "12345"]

使用上面的我有错误:

[“api_key”:“mykey123”,“密码”:“flibble1”,“uniqueid”:“csd23cdse34ww”,“api_secret”:“secret123”,“pin”:“12345”] 2019-01-25 10:00:54.298086+0000 APPTEST[8863:646933] [日志] 表“用户”已经存在 表“用户”已经存在(代码:1)。
/todos 上的 POST 解析响应时出错

在邮递员身上工作得很好

'{ "api_key": "mykey123", “api_secret”:“asdfg”, "uniqueid": "csd23cdse34ww", “密码”:“secret123”, “销”:“12345”, }'

但是 Xcode 要求我使用下面的语法。

func loginPressed() {
    let todosEndpoint: String = "https://mydevapi.com/authenticateuser"
    guard let todosURL = URL(string: todosEndpoint) else {
        print("Error: cannot create URL")
        return
    }
    var todosUrlRequest = URLRequest(url: todosURL)
    todosUrlRequest.httpMethod = "POST"

    let newTodo = "{\"api_key\":\"mykey123\",\"api_secret\":\"asdfg\",\"uniqueid\":\"csd23cdse34ww\",\"password\":\"secret123\",\"pin\":\"12345\"}"

    let jsonTodo: Data
    do {
        jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
        todosUrlRequest.httpBody = jsonTodo
        print(newTodo)
    } catch {
        print("Error: cannot create JSON from todo")
        return
    }

    let session = URLSession.shared

    let task = session.dataTask(with: todosUrlRequest) {
        (data, response, error) in
        guard error == nil else {
            print("error calling POST on /todos/1")
            print(error!)
            return
        }
        guard let responseData = data else {
            print("Error: did not receive data")
            return
        }

        // parse the result as JSON, since that's what the API provides
        do {
            guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: Any] else {
                    print("Could not get JSON from responseData as dictionary")
            return
            }
            print(receivedTodo)
            print("The todo is: " + receivedTodo.description)

            guard let todoID = receivedTodo["id"] as? Int else {
                print("Could not get todoID as int from JSON")
                print(receivedTodo)
                return
            }
            print("The ID is: \(todoID)")
            print(receivedTodo)
        } catch  {
            print("error parsing response from POST on /todos")
            return
        }
    }
    task.resume()
}

应用程序崩溃 - 线程 1:信号 SIGABRT

2019-01-25 09:37:05.762339+0000 APPTEST[8601:615340] * 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'* +[NSJSONSerialization dataWithJSONObject:options:错误:]:JSON 写入中的顶级类型无效' *** 首先抛出调用堆栈: ( 0 核心基础 0x00000001087f11bb 异常预处理 + 331 1 libobjc.A.dylib 0x000000010635f735 objc_exception_throw + 48 2 核心基础 0x00000001087f1015 +[NSException raise:format:] + 197 3 基础 0x0000000105eb2dd5 +[NSJSONSerialization dataWithJSONObject:options:error:] + 253 4 APPTEST 0x000000010588ab5e $S9Bibimoney15LoginControllerC12loginPressedyyF + 2718 5 APPTEST 0x000000010588f79c $STA.7 + 28 6 APPTEST 0x00000001058924d4 $S9Bibimoney9LoginViewC06handleB0yyF + 132 7 APPTEST 0x0000000105892534 $S9Bibimoney9LoginViewC06handleB0yyFTo + 36 8 UIKitCore 0x000000010c876ecb-[UIApplication sendAction:to:from:forEvent:] + 83 9 UIKitCore 0x000000010c2b20bd-[UIControl sendAction:to:forEvent:] + 67 10 UIKitCore 0x000000010c2b23da-[UIControl _sendActionsForEvents:withEvent:] + 450 11 UIKitCore 0x000000010c2b131e -[UIControl touchesEnded:withEvent:] + 583 12 UIKitCore 0x000000010c8b20a4 -[UIWindow_sendTouchesForEvent:] + 2729 13 UIKitCore 0x000000010c8b37a0 -[UIWindow 发送事件:] + 4080 14 UIKitCore 0x000000010c891394-[UIApplication sendEvent:] + 352 15 UIKitCore 0x000000010c9665a9 __dispatchPreprocessedEventFromEventQueue + 3054 16 UIKitCore 0x000000010c9691cb __handleEventQueueInternal + 5948 17 核心基础 0x0000000108756721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17 18 核心基础 0x0000000108755f93 __CFRunLoopDoSources0 + 243 19 核心基础 0x000000010875063f __CFRunLoopRun + 1263 20 核心基础 0x000000010874fe11 CFRunLoopRunSpecific + 625 21 图形服务 0x000000011047c1dd GSEventRunModal + 62 22 UIKitCore 0x000000010c87581d UIApplicationMain + 140 23 APPTEST 0x0000000105896517 主要 + 71 24 libdyld.dylib 0x0000000108d93575 开始 + 1 25 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib:以 NSException 类型的未捕获异常终止 (lldb)

  • 预期状态码 200

【问题讨论】:

  • 究竟是哪一行导致了崩溃?崩溃的完整错误消息是什么?
  • 你有没有看到这个服务器请求被正确处理(一些现有的网络客户端或其他东西)?你可以记录请求-响应,然后记录新客户的请求-响应并比较它们吗?
  • 对不起各位,第一次在这里发帖。我刚刚编辑了帖子。谢谢你。对不起@ycnix,但我不知道该怎么做。我能怎么做?我刚开始使用这些工具,对不起。
  • 以 Wireshark 为例。启动 Wireshark,设置其捕获过滤器(端口和主机),然后使用浏览器访问您的 Web 服务。
  • 看到帧后,右键单击其中一个帧并选择“跟随 TCP 流”

标签: arrays json swift post httprequest


【解决方案1】:

我很确定您没有发送您期望的内容。看起来您尝试对“已经是”JSON 的字符串进行 JSON 编码。你应该打印出你的jsonTodo 的内容(你会惊讶于你会看到多少转义......)。如果您将Dictionary 传递给JSONSerialization,它可能会做正确的事情,但通过JSONDecoderCodeable 协议执行此类转换要快得多。 p>

您应该将您的问题简化为手头的实际问题,以便人们提供帮助。尝试专注于在您的 Data 对象中创建正确的 JSON,一旦您知道事情就会落实到位。

为了得到您当前问题的具体答案,您应该使用jsonTodo 的内容修改您的问题。

【讨论】:

    猜你喜欢
    • 2011-07-02
    • 2017-02-12
    • 2011-05-08
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多