jsonpropertyname 特性优先于命名策略。当两者同时存在时,序列化器会直接使用特性指定的名称,完全忽略命名策略的转换规则。

System.Text.Json中特性与策略的冲突处理
在 System.Text.Json 中,JsonPropertyNameAttribute 用于显式指定属性在 JSON 中的键名。如果配置了 JsonNamingPolicy(如 JsonNamingPolicy.CamelCase),该策略仅对未标记 JsonPropertyName 的属性生效。对于已标记特性的属性,策略会被跳过。

using System;
using System.Text.Json;
public class User
{
[JsonPropertyName("user_id")]
public int Id { get; set; }
public string Name { get; set; }
}
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var user = new User { Id = 1, Name = "Alice" };
var json = JsonSerializer.Serialize(user, options);
Console.WriteLine(json); // 输出: {"user_id":1,"name":"Alice"}运行上述代码,输出结果为 {"user_id":1,"name":"Alice"}。Id 属性保持为 user_id,而 Name 属性被转换为 name。这证实了特性具有最高优先级。
Newtonsoft.Json中的行为对比
在 Newtonsoft.Json 中,类似的行为由 [JsonProperty] 特性控制。如果设置了全局命名约定(如 ContractResolver 或 DefaultCamelCasePropertyNamesContractResolver),[JsonProperty] 同样会覆盖默认行为。
一个基于官方 Mailtrap Node.js SDK 构建的 ASE 技能,用于发送事务邮件并与 Mailtrap 沙盒或生产流程协作。它非常适合需要 API 驱动邮件投递、测试邮箱验证和结构化消息自动化的代理工作流。

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
public class Product
{
[JsonProperty("prod_code")]
public string Code { get; set; }
public decimal Price { get; set; }
}
var settings = new JsonSerializerSettings
{
ContractResolver = new DefaultCamelCasePropertyNamesContractResolver()
};
var product = new Product { Code = "A1", Price = 10.5m };
var json = JsonConvert.SerializeObject(product, settings);
Console.WriteLine(json); // 输出: {"prod_code":"A1","price":10.5}执行后输出为 {"prod_code":"A1","price":10.5}。Code 使用特性指定的 prod_code,Price 被解析为 price。这与 System.Text.Json 的逻辑一致,即显式特性优先于全局策略。
当特性值为空字符串时的具体表现
如果 JsonPropertyName 的值设置为空字符串 "",序列化器会将其视为有效的键名,而不是回退到命名策略。这意味着属性在 JSON 中将表现为一个空键。
using System;
using System.Text.Json;
public class EmptyKeyTest
{
[JsonPropertyName("")]
public string Value { get; set; }
}
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var obj = new EmptyKeyTest { Value = "test" };
var json = JsonSerializer.Serialize(obj, options);
Console.WriteLine(json); // 输出: {"":"test"}在此情况下,输出为 {"":"test"}。空字符串被直接用作键,命名策略未生效。这种行为可能导致某些 JSON 解析器报错,因为空键通常不符合规范。开发者应避免使用空字符串作为特性值,除非明确需要这种非标准行为。

















