首页 新闻 会员 周边

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

0
悬赏园豆:30 [已解决问题] 解决于 2022-01-02 10:26

将一个项目升级到 .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()

请问如何解决?

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2022-01-01 23:05
< >
分享
最佳答案
0

通过 JsonNumberHandling.AllowReadingFromString 选项可以解决

return await response.Content.ReadFromJsonAsync<IEnumerable<BlogPostZzkDoc>>(
    new JsonSerializerOptions { NumberHandling = JsonNumberHandling.AllowReadingFromString });
dudu | 高人七级 |园豆:30994 | 2022-01-02 10:25

上面的解决方法针对的不是提问中的场景,详见 Non-string values for string properties

dudu | 园豆:30994 (高人七级) | 2022-01-02 23:16
其他回答(1)
0

目前的解决办法就是一写自定义的转换器,二是修改model中属性类型,STJ对序列化这块控制的比较死,这也是它高性能的原因,要求严格的匹配。

some-body | 园豆:242 (菜鸟二级) | 2022-01-05 10:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册