JSON的语法-正文发布请求-SWIFT4

时间:2019-01-24 17:03:50

标签: arrays json swift post httprequest

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

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

  

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

  

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

由于上述原因,我出现了错误:

  

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

在Postman身上可以很好地工作

  

'{       “ api_key”:“ mykey123”,       “ api_secret”:“ asdfg”,       “ uniqueid”:“ csd23cdse34ww”,       “ password”:“ secret123”,       “ pin”:“ 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 CoreFoundation 0x00000001087f11bb exceptionPreprocess + 331     1 libobjc.A.dylib 0x000000010635f735 objc_exception_throw + 48     2 CoreFoundation 0x00000001087f1015 + [NSException提高:格式:] + 197     3 Foundation 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 sendEvent:] + 4080     14 UIKitCore 0x000000010c891394-[UIApplication sendEvent:] + 352     15 UIKitCore 0x000000010c9665a9 __dispatchPreprocessedEventFromEventQueue + 3054     16 UIKitCore 0x000000010c9691cb __handleEventQueueInternal + 5948     17 CoreFoundation 0x0000000108756721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17     18 CoreFoundation 0x0000000108755f93 __CFRunLoopDoSources0 + 243     19 CoreFoundation 0x000000010875063f __CFRunLoopRun + 1263     20 CoreFoundation 0x000000010874fe11 CFRunLoopRunSpecific + 625     21 GraphicsServices 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

1 个答案:

答案 0 :(得分:0)

我很确定您没有寄出您所期望的。似乎您尝试对“已经是” JSON的字符串进行JSON编码。您应该打印出jsonTodo的内容(您会惊讶地发现会有多少转义。)。如果将JSONSerialization传递给DictionaryJSONDecoder可能会做正确的事情,但是通过Codeable和{ {1}}协议。

您应该将问题简化为当前的实际问题,以便人们提供帮助。一旦掌握了一切,就可以尝试集中精力在Data对象中创建正确的JSON。

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