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

.Net C# 使用Newtonsoft反序列化时default属性无法获取值问题

问题根因
  • 你使用的 [JsonPropertyName] 特性属于 .NET 内置的 System.Text.Json 序列化库,Newtonsoft.Json 不识别该特性,因此无法完成 JSON 中 default 字段和实体类 defaultValue 属性的映射,导致无法获取对应值。
解决方案

方案1:替换为Newtonsoft.Json专属特性

将实体类的特性替换为 Newtonsoft.Json 自带的 [JsonProperty] 即可,修改后的实体类代码如下:

using Newtonsoft.Json;

public class ItemProperties
{
   public string displayName { get; set; }
   public string name { get; set; }
   public string type { get; set; }

   [JsonProperty("default")]
   public dynamic defaultValue{ get; set; }
}

方案2:双特性兼容(适配两种序列化库)

如果你的项目中同时使用 System.Text.Json 和 Newtonsoft.Json,可以同时加两个特性实现兼容:

using Newtonsoft.Json;
using System.Text.Json.Serialization;

public class ItemProperties
{
   public string displayName { get; set; }
   public string name { get; set; }
   public string type { get; set; }

   [JsonProperty("default")]
   [JsonPropertyName("default")]
   public dynamic defaultValue{ get; set; }
}
补充说明
  • default 是 C# 内置关键字,如果你不想用特性映射,也可以将属性名转义命名为 @default,无需额外加特性也能正常映射:
public dynamic @default { get; set; }
  • 若修改后仍无法获取值,可以检查反序列化配置是否开启了空值忽略,确认 NullValueHandling 没有设置为 Ignore 即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:15:01