JSONSerialization Invalid type in JSON write (_SwiftValue)

前端 未结 10 919
情书的邮戳
情书的邮戳 2020-12-14 14:14

Why does the following code give me the error:

Invalid type in JSON write (_SwiftValue).

The error is thrown on this line:

相关标签:
10条回答
  • 2020-12-14 14:34

    I was getting this runtime error because my dictionary was like this:

    var dictionary: [AnyHashable: Any] = [:]
    let elapsedTime = Date.timeIntervalSince(oldDate)
    dictionary["elapsedTime"] = elapsedTime
    

    Can you tell me what the problem is? hover your mouse on the box below to see answer!

    elapsedTime's type is Function it's not TimeInterval. I needed to change Date. to Date(). ie use the instance method rather than the static method. When you're dictionary values are Any then this sort of issue doesn't get found until a runtime error where it can't serialize the dictionary to a JSON string...

    0 讨论(0)
  • 2020-12-14 14:35

    Had the same problem and error as you! FINALLY found the issue...

    My code:

    params = [
        "gender": request.gender.first ?? "",
        "age": 15
    ]
    

    Problem: Even though request.gender.first ?? "" returns a string, its a type of String.Element, which ANY JSONEncoder or JSONSerialization cannot encode (and is not in the list of types it can handle, according to documentation).

    Solution:

    params = [
        "gender": request.gender.first?.description ?? "",
        "age": 15
    ]
    

    Typically, just make sure its a string or an appropriate number the Encoders can handle...

    0 讨论(0)
  • 2020-12-14 14:38

    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]
    
    0 讨论(0)
  • 2020-12-14 14:45

    I got this error when used a Set that is linked with Foundation NSSet.

    let myArray = Array(mySet)
    
    0 讨论(0)
提交回复
热议问题