You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用FSharp.SystemTextJson反序列化时未指定字段转None报错求助

问题

查阅FSharp.SystemTextJson的文档后,我认为可将反序列化时未指定的JSON字段转为Option.None,但运行修改后的测试代码时却抛出异常。测试代码如下:

#r "nuget: FSharp.SystemTextJson"

open System.Text.Json
open System.Text.Json.Serialization

type Point() =
    member val X = 0. with get, set
    member val Y = 0. with get, set

type Rectangle =
    { BottomLeft: Point option // <-- 标记为可选
      TopRight: Point }

let fsoptions =
    JsonFSharpOptions()
      .WithAllowNullFields(true) //测试中设为true或false均无影响

let options = fsoptions.ToJsonSerializerOptions()
options.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase //需要支持驼峰命名

//JSON中缺少BottomLeft字段,反序列化器应将其转为None
JsonSerializer.Deserialize<Rectangle>("""{"topRight":{"x":1,"y":2}}""", options)

抛出的异常信息:

System.Text.Json.JsonException: Missing field for record type FSI_0045+Rectangle: bottomLeft at System.Text.Json.Serialization.Helpers.failf@12.Invoke(String x) at System.Text.Json.Serialization.JsonRecordConverter1.ReadRestOfObject(Utf8JsonReader& reader, Boolean skipFirstRead) in /home/runner/work/FSharp.SystemTextJson/FSharp.SystemTextJson/src/FSharp.SystemTextJson/Record.fs:line 203 at System.Text.Json.Serialization.JsonRecordConverter1.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options) in /home/runner/work/FSharp.SystemTextJson/FSharp.SystemTextJson/src/FSharp.SystemTextJson/Record.fs:line 180

我之前使用NewtonSoft.Json + FSharpLu.Json可实现该功能,现迁移到System.Text.Json + FSharp.SystemTextJson后遇此问题,且未找到相关设置,请问我遗漏了什么?

解决方案

你需要在JsonFSharpOptions中启用WithMissingFieldIsNone(true)配置,这是FSharp.SystemTextJson专门用来处理record中缺失字段映射为Option.None的开关,默认是关闭的。

修改后的fsoptions代码如下:

let fsoptions =
    JsonFSharpOptions()
      .WithAllowNullFields(true)
      .WithMissingFieldIsNone(true) // 新增该配置项

启用该配置后,当JSON中缺少BottomLeft字段时,反序列化器会自动将其赋值为None,不会再抛出缺失字段的异常。

内容的提问来源于stack exchange,提问作者Juan Paredes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:10:09