JSONSerialization Invalid type in JSON write (_SwiftValue)
Solution 1:
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 of NSString
, NSNumber
, NSArray
, NSDictionary
, or NSNull
. As given in the documentation for JSONSerialization
class:
An object that may be converted to JSON must have the following properties:
The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString. Numbers are not NaN or infinity.
Other rules may apply. Calling isValidJSONObject(_:) or attempting a conversion are the definitive ways to tell if a given object can be converted to JSON data.
So, please check if any of the objects in your parameters
object doesn't satisfy the above constraints.
Solution 2:
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"
Solution 3:
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:
enum Status: String {
case open
case closed
}
instead of passing the enum:
params = ["status": Status.open]
pass
params = ["status": Status.open.rawValue]
Solution 4:
You can call this method too and see if your parameter can be converted to a JSON object, this will return a Bool.
let checker = JSONSerialization.isValidJSONObject(parameters)
Solution 5:
In my case I accidentally added an object to the Parameters dictionary instead of a string