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

如何将JSON反序列化为Dictionary<string, object>并获取原生值类型?

解决System.Text.Json反序列化为Dictionary<string, object>时返回JsonElement的问题

当你使用System.Text.Json将JSON反序列化为Dictionary<string, object>时,默认情况下反序列化器会把值包装为JsonElement类型,而非原生的string、bool等值类型。针对你确认字典中无复杂子对象的场景,可以通过以下方法解决:

方法一:配置JsonSerializerOptions的UnknownTypeHandling

修改反序列化代码,添加JsonSerializerOptions并设置UnknownTypeHandling = JsonUnknownTypeHandling.Object,这样反序列化器会自动将JSON值转换为对应的CLR原生类型:

[Fact]
public void MyTestMethod()
{
    // Arrange
    var input = @"
    {
        ""Key1"":""Value1"",
        ""Key2"":true
    }";

    // Act
    var options = new JsonSerializerOptions
    {
        UnknownTypeHandling = JsonUnknownTypeHandling.Object
    };
    var obj = JsonSerializer.Deserialize<Dictionary<string, object>>(input, options)!;

    // Assert
    Assert.Equal(typeof(string), obj["Key1"].GetType());
    Assert.Equal(typeof(bool), obj["Key2"].GetType());
}

方法二:使用JsonNode转换(.NET 6+)

如果你使用的是.NET 6或更高版本,也可以先将JSON反序列化为JsonNode,再转换为Dictionary<string, object>,同样能得到原生值类型:

[Fact]
public void MyTestMethod()
{
    // Arrange
    var input = @"
    {
        ""Key1"":""Value1"",
        ""Key2"":true
    }";

    // Act
    var jsonNode = JsonNode.Parse(input)!;
    var obj = jsonNode.Deserialize<Dictionary<string, object>>()!;

    // Assert
    Assert.Equal(typeof(string), obj["Key1"].GetType());
    Assert.Equal(typeof(bool), obj["Key2"].GetType());
}

原理说明

System.Text.Json默认用JsonElement处理object类型,是为了保留JSON的原始结构和类型信息,避免在有复杂嵌套对象时丢失数据。当你确认没有复杂子对象时,通过上述配置可以让反序列化器直接映射到原生值类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 14:29:10