Why does the following code give me the error:
Invalid type in JSON write (_SwiftValue).
The error is thrown on this line:
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters)
Full code:
let parameters:Parameters = ["resource":[
[
"appUserCode":uuidString,
"productNFCode": self.nfCode!,
"status":code,
"applicationKey":appDelegate.api_key
]
]
]
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters)
} catch {
// No-op
}
I had this problem and it was because one of my strings was Optional. It was trying to serialize a value like: "Optional(\"string value\")"
Instead of "string value"
If your problem is still not resolved by the answer given here. I believe one of your objects inside the
parameters
might not be an instance ofNSString
,NSNumber
,NSArray
,NSDictionary
, orNSNull
. As given in the documentation forJSONSerialization
class:So, please check if any of the objects in your
parameters
object doesn't satisfy the above constraints.Just in case anyone is still having problems and is using Enums, another cause may be if you are passing an Enum value and not it's rawValue.
Example:
instead of passing the enum:
pass
You should convert
NSObject
toNSDictionary
at firstTry this to convert to
NSDictionary
.Then call this:
If you're using SwiftyJSON to access a JSON object, it's important to use the
dictionaryObject
property of the JSON (instead of usingdictionaryValue
,dictionary
or nothing at all), because you will get this error (or a variation of it) otherwise. For example: