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

如何配置System.Text.Json序列化F#记录的自引用成员

问题场景

F#开发中给记录类型定义自引用派生成员时,NewtonSoft.Json可正常序列化输出这类成员,但迁移到System.Text.Json后,序列化结果默认不包含这类成员。
复现代码:

type Payload =
    { Id: Guid }
    member x.DerivedProperty = $"Derived Property using id: {x.Id}"

排查确认:该问题是引入FSharp.SystemTextJson库后产生的默认行为差异,不使用FSharp.SystemTextJson时,原生System.Text.Json序列化结果符合预期。

解决方法

原生System.Text.Json(无FSharp.SystemTextJson依赖)

原生System.Text.Json默认序列化所有公共可读属性,上述DerivedProperty会被正常输出,不需要额外特殊配置。如果遇到不输出的情况,检查JsonSerializerOptions的IgnoreReadOnlyProperties配置项是否被异常修改即可。

引入FSharp.SystemTextJson后的变通方案

FSharp.SystemTextJson默认仅序列化记录类型的声明字段,会忽略自定义附加成员,有两种可行方案:

  • 全局配置开启公共属性序列化
    初始化Json序列化选项时,打开公共属性包含开关即可:
    let jsonOptions = 
        JsonFSharpOptions.Default()
            .WithIncludePublicProperties(true)
            .ToJsonSerializerOptions()
    // 序列化时传入该配置即可正常输出自定义成员
    JsonSerializer.Serialize(payload, jsonOptions)
    
  • 给需要序列化的成员单独打标记
    如果不想全局开启公共属性扫描,只需要给要输出的自定义成员添加JsonPropertyName特性即可:
    open System.Text.Json.Serialization
    type Payload =
        { Id: Guid }
        [<JsonPropertyName("derivedProperty")>]
        member x.DerivedProperty = $"Derived Property using id: {x.Id}"
    
    打标后FSharp.SystemTextJson会识别该成员为序列化目标,不受全局配置影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 08:00:36