JSONSerialization Invalid type in JSON write (_SwiftValue)

前端 未结 10 941
情书的邮戳
情书的邮戳 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: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...

提交回复
热议问题