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

如何在C#中反序列化包含"."的JSON键?

解决方案:处理JSON中含点的字段名

我太懂这种尴尬了!C#的标识符规则确实不允许属性名以点开头,但咱们可以借助序列化库的特性来完美解决这个问题,给你两种最常用的方案:

方案一:使用Newtonsoft.Json(Json.NET)

这是.NET生态里最常用的JSON序列化库,你只需要给属性加上[JsonProperty]特性,指定它对应的JSON字段名就行,属性本身用合法的C#命名:

using Newtonsoft.Json;

public class Authentication
{
    public string usertoken { get; set; }
    public int expires_sec { get; set; }
    public string user { get; set; }
    
    // 用特性映射JSON里的.expired字段
    [JsonProperty(".expired")]
    public string Expired { get; set; }
}

方案二:使用System.Text.Json(.NET Core/.NET 5+自带)

如果你用的是较新的.NET版本,直接用系统自带的序列化库就可以,用[JsonPropertyName]特性实现同样的映射:

using System.Text.Json.Serialization;

public class Authentication
{
    public string usertoken { get; set; }
    public int expires_sec { get; set; }
    public string user { get; set; }
    
    // 特性指定JSON字段名,属性名用合法的名称
    [JsonPropertyName(".expired")]
    public string Expired { get; set; }
}

额外提示

你也可以把属性名改成和其他字段一致的小写风格(比如expired),只要特性里的字段名准确对应JSON的.expired就没问题,完全不影响反序列化效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:53:54