Invalid type in JSON write (_SwiftValue) using Alamofire

Ramon picture Ramon · Sep 20, 2016 · Viewed 9k times · Source

I have tried a lot of things now and are still getting: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'

UPDATE: I scan a barcode and save the info:

let calendar = Calendar.current
let expiryDate = (calendar as NSCalendar).date(byAdding: .month, value: 3, to: Date(), options: [])?.description

let barcode = BarcodeData(barcodeValue: value,
                          datetime: dateTime,
                          expiryDate: expiryDate!,
                          latitude: latitude.description,
                          longitude: longitude.description,
                          status: txtStatus.text!,
                          type: txtType.text!,
                          extraText: "")

Object are then mapped to a JSON string, it seems that the slashes (/) are added by this function:

let jsonBarcode = Mapper<BarcodeData>().toJSONString(barcode)

The barcode are then added to a list of String:

barcodeDataList.append(jsonBarcode)

When I click a button I invoke the web service, that anticipate parameters in the form of:

let testParams : Parameters =
    [ "udid": "my_udid",
       "data": jsonArray
    ]

jsonArray consist of an array of the BarcodeData-object(s) as seen above.

Communication with the web service looks like:

Alamofire.request(url, method: .post, parameters: testParams, encoding: JSONEncoding.default).validate().responseJSON { response in

                switch response.result {
                case .success:
                    print("Validation successful")

                    if let json = response.result.value {
                        print("JSON: \(json)")
                    }

                case .failure(let error):
                    print("Error: \(error)")
                }
            }

The following is passed to the ws:

    ["udid": "\"001-my_udid\"", "data": [
    "{\"latitude\":\"0.0\",\"status\":\"Empty\",\"datetime\":\"2016-09-20 05:10\",\"longitude\":\"0.0\",\"type\":\"ABC123\",\"barcodevalue\":\"123456\"}"
]]

The json array for "data" validates at jsonlint.com and the response from the server is in the form of a json object like:

{result: "Data successfully received"}

Answer

Abhilasha Thapliyal picture Abhilasha Thapliyal · Dec 8, 2016

Change your encoding in request from encoding: JSONEncoding.default to encoding: URLEncoding.default