Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

alamofire - JSONSerialization Invalid type in JSON write (_SwiftValue)

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
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  1. The top level object is an NSArray or NSDictionary. All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  2. All dictionary keys are instances of NSString. Numbers are not NaN or infinity.

  3. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...