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

在C#中,如何使用JsonSerializer.DeserializeAsync反序列化含私有构造函数的对象?

解决私有构造函数类的System.Text.Json反序列化问题

针对你遇到的无法修改Text类但需要反序列化的场景,可以通过自定义Json转换器绕过公共构造函数的限制,以下是两种可行方案:

方案一:反射调用私有构造函数

直接通过反射获取Text的私有构造函数并实例化对象,适合不需要复用类本身验证逻辑的场景:

public class TextJsonConverter : JsonConverter<Text>
{
    public override Text Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        // 读取JSON中的Value字段值
        string value = reader.GetString() ?? string.Empty;
        
        // 获取私有构造函数(参数类型为string)
        var constructor = typeof(Text).GetConstructor(
            BindingFlags.NonPublic | BindingFlags.Instance,
            new[] { typeof(string) });
        
        if (constructor == null)
        {
            throw new JsonException("无法找到Text类的私有构造函数");
        }
        
        // 调用构造函数创建实例
        return (Text)constructor.Invoke(new object[] { value });
    }

    public override void Write(Utf8JsonWriter writer, Text value, JsonSerializerOptions options)
    {
        // 序列化时直接输出Value字段
        writer.WriteStringValue(value.Value);
    }
}

使用时将转换器添加到JsonSerializerOptions中:

var _options = new JsonSerializerOptions();
_options.Converters.Add(new TextJsonConverter());

var texts = await JsonSerializer.DeserializeAsync<ImmutableArray<Text>>(stream, _options);

方案二:调用静态Create工厂方法

如果需要遵循Text类本身的验证逻辑(比如长度检查),可以在转换器中调用Create方法,确保实例符合领域规则:

public class TextJsonConverter : JsonConverter<Text>
{
    public override Text Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        string value = reader.GetString() ?? string.Empty;
        
        // 调用静态Create方法
        var resultMethod = typeof(Text).GetMethod("Create", new[] { typeof(string) });
        if (resultMethod == null)
        {
            throw new JsonException("无法找到Text类的Create静态方法");
        }
        
        var result = (Result<Text>)resultMethod.Invoke(null, new object[] { value });
        
        // 处理Create方法的返回结果
        if (result.IsFailure)
        {
            throw new JsonException($"创建Text实例失败:{result.Error.Message}");
        }
        
        return result.Value;
    }

    public override void Write(Utf8JsonWriter writer, Text value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.Value);
    }
}

注意:此方案会严格执行Create方法中的验证逻辑,如果反序列化的字符串不符合要求(比如为空或长度不足),会抛出异常,需根据业务场景处理错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 16:13:40