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

.NET Core 3.1通用JSON序列化问题:传入Object返回空JSON

解决System.Text.Json序列化Object参数生成空JSON的问题

这个问题的核心原因很明确:System.Text.Json序列化器需要明确知道目标对象的具体类型。当你把方法参数声明为Object obj时,序列化器只能识别到它是基础的object类型——而object本身没有公共属性,自然就生成空的{}了。不用为每个类单独编写序列化方法的最简方案,就是通过泛型方法保留类型信息,或者在运行时手动指定类型参数。

方案1:使用泛型方法(推荐,最简洁)

泛型会在编译时自动捕获对象的具体类型,让序列化器能正确识别并序列化类中的字段/属性:

using System.Text.Json;
using System.IO;

public class AppEntry
{
    // 通用泛型序列化方法,支持任意可序列化类型
    public void SerializeToJson<T>(T obj, string outputPath)
    {
        var serializeOptions = new JsonSerializerOptions
        {
            WriteIndented = true, // 可选:生成格式化的JSON,方便阅读
            IncludeFields = true  // 如果你的配置类用字段而非属性,必须开启这个
        };
        
        string jsonContent = JsonSerializer.Serialize(obj, serializeOptions);
        File.WriteAllText(outputPath, jsonContent);
    }

    // 启动入口示例
    public static void Main(string[] args)
    {
        var appSettings = new Settings { MaxRetryCount = 3, ConnectionTimeout = 5000 };
        var entry = new AppEntry();
        
        // 直接传入对象,泛型自动推导类型
        entry.SerializeToJson(appSettings, "appConfig.json");
    }
}

// 你的配置类示例
public class Settings
{
    public int MaxRetryCount { get; set; }
    public int ConnectionTimeout { get; set; }
}

方案2:运行时指定类型(适用于动态类型场景)

如果你的对象类型是运行时才确定的(比如从反射获取的类型),没办法用泛型,可以调用JsonSerializer.Serialize的重载,手动传入Type参数:

public void SerializeDynamicObject(object obj, Type targetType, string outputPath)
{
    var serializeOptions = new JsonSerializerOptions { WriteIndented = true };
    string jsonContent = JsonSerializer.Serialize(obj, targetType, serializeOptions);
    File.WriteAllText(outputPath, jsonContent);
}

// 调用示例
SerializeDynamicObject(appSettings, typeof(Settings), "appConfig.json");

关键注意事项

  • 确保配置类的成员是公共的:System.Text.Json默认只序列化公共属性/字段;
  • 如果用字段而非属性存储配置,一定要在JsonSerializerOptions中设置IncludeFields = true;
  • .NET Core 3.1的System.Text.Json对部分复杂类型(比如私有成员、继承类型)支持有限,若遇到特殊需求,可以通过[JsonPropertyName]等特性手动指定序列化规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:37:17