Home > Mobile >  JSON Write throws invalid type
JSON Write throws invalid type

Time:11-21

When I try to write some data for some ML Inside of a api, like in Postman, the entry works, but for some reason, when I write it in Swift I am having some trouble:

func makePOSTRequest() {
        
        print("entered request function")
        
        guard let url = URL(string: "https://doctagon.herokuapp.com/diagnose") else {
            print("error with getting the URL")
            return
        }
        print("got the URL")
        
        var request = URLRequest(url: url)
        print("Got the request")
        // method, body, headers?
        request.httpMethod = "POST"
        print("got the http.method = 'POST'")
        
        // might not need this --> request.setValue(" symptoms", forHTTPHeaderField: "Content-Type")
        let body: [String: AnyHashable] = [
            "symptoms": ["Headache", "Sweating"]
        ]
        print("got the body")
        
        print("About to enter the .httpBody part of the code")
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
        //Make the request
        let task = URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data, error == nil else {
                print("error with making sure that there is data")
                return
            }
            print("got data")
            do {
                let response = try JSONSerialization.data(withJSONObject: data, options: .fragmentsAllowed)
                print("SUCCESS \(response)")
            } catch {
                print("error with the conversion of the JSOn")
                print(error)
            }
        }
        task.resume()
        print("resumed Task")
    }

with my error:

2022-11-19 23:39:30.335160-0500 Doctagon[88188:1838200] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation.__NSSwiftData)'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000018040e7ec __exceptionPreprocess   172
    1   libobjc.A.dylib                     0x0000000180051144 objc_exception_throw   56
    2   Foundation                          0x0000000180c446f8 _writeJSONValue   704
    3   Foundation                          0x0000000180c443f8 -[_NSJSONWriter dataWithRootObject:options:]   84
    4   Foundation                          0x0000000180c470d0  [NSJSONSerialization dataWithJSONObject:options:error:]   108
    5   Doctagon                            0x0000000100be4080 $s8Doctagon12QuestionViewV15makePOSTRequestyyFy10Foundation4DataVSg_So13NSURLResponseCSgs5Error_pSgtYbcfU_   544
    6   Doctagon                            0x0000000100be45ec $s10Foundation4DataVSgSo13NSURLResponseCSgs5Error_pSgIeghggg_So6NSDataCSgAGSo7NSErrorCSgIeyBhyyy_TR   264
    7   CFNetwork                           0x0000000183df9928 CFNetwork   31016
    8   CFNetwork                           0x0000000183e14a4c _CFHTTPMessageSetResponseProxyURL   14648
    9   libdispatch.dylib                   0x0000000104c30594 _dispatch_call_block_and_release   24
    10  libdispatch.dylib                   0x0000000104c31d5c _dispatch_client_callout   16
    11  libdispatch.dylib                   0x0000000104c3a040 _dispatch_lane_serial_drain   928
    12  libdispatch.dylib                   0x0000000104c3adb8 _dispatch_lane_invoke   484
    13  libdispatch.dylib                   0x0000000104c48b40 _dispatch_workloop_worker_thread   1720
    14  libsystem_pthread.dylib             0x00000001af2568fc _pthread_wqthread   284
    15  libsystem_pthread.dylib             0x00000001af2556c0 start_wqthread   8
)
libc  abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation.__NSSwiftData)'
terminating with uncaught exception of type NSException
CoreSimulator 857.13 - Device: iPhone 14 Pro (4108291D-D836-4715-8386-5237B6D217E7) - Runtime: iOS 16.1 (20B72) - DeviceType: iPhone 14 Pro

I still do not understand my problem because I was able to run it fine in Postman, but as soon as I went into Xcode, the code stopped working.

I think that the error is on this line: let response = try JSONSerialization.data(withJSONObject: data, options: .fragmentsAllowed)

CodePudding user response:

what you are trying to do is create a json object (in this case it will be an instance of Dictionary<String: Any>) using the data received from the network so you should be calling JSONSerialization.jsonObject(with: data) instead.

  • Related