System.Text.Json 反序列化错误:”Cannot get the value of a token type ‘Number’ as a string”

将一个项目升级到 .NET 6 后,执行 response.Content.ReadFromJsonAsync 时出现错误:

System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $[0].id | LineNumber: 0 | BytePositionInLine: 907.
---> System.InvalidOperationException: Cannot get the value of a token type 'Number' as a string.
at System.Text.Json.Utf8JsonReader.GetString()

请问如何解决?

回答

通过 JsonNumberHandling.AllowReadingFromString 选项可以解决

return await response.Content.ReadFromJsonAsync<IEnumerable<BlogPostZzkDoc>>(
    new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString });
以上是System.Text.Json 反序列化错误:”Cannot get the value of a token type ‘Number’ as a string”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>