问题描述
在我们的Web API中,我们有具有缩写名称的旧实体。我们还通过T4模板使用代码生成,我们希望使代码保持简单和可预测:
但是,Web API的JSON响应在决定将哪些字母转换为小写字母而不是仅转换预期的第一个字符方面具有神奇的作用。
例如,在Visual Studio中启动新的默认Web API并将两个属性添加到WeatherForecast.cs
时:
public string TSTValue { get; set; }
public string TSTVL1 { get; set; }
结果是:
[
{
...
"tstValue":null,"tstvL1":null
},{
...
"tstValue":null,"tstvL1":null
}
]
[
{
...
"tSTValue":null,"tSTVL1":null
},{
...
"tSTValue":null,"tSTVL1":null
}
]
如何取消魔术行为?
解决方法
首先,您描述的行为是有意的。您可以在Github https://github.com/dotnet/runtime/blob/master/src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonCamelCaseNamingPolicy.cs上查看源代码,幸好可以相对轻松地自定义名称序列化。
由于您指定了不使用属性,因此可以创建自己的JsonNamingPolicy
,该属性可以用来以您认为合适的方式序列化字段名称。
下面,我创建了一个基本类,该类确保第一个字符为小写字母,并保留其余的字段字符串。将为序列化类中的每个字段调用ConvertName(string name)
。在您的示例中,TSTValue
和TSTVL1
public class JsonFirstCharToLowerNamingPolicy : JsonNamingPolicy
{
public override string ConvertName(string name)
{
// if the string is empty or the first character is already lowercase just return as is
if (string.IsNullOrEmpty(name) || char.IsLower(name[0]))
return name;
char[] chars = name.ToCharArray(); // get a list of chars
chars[0] = char.ToLowerInvariant(chars[0]); // make the first character lower case
// leave the rest of the characters alone or do more processing on it?
return new string(chars); // return the altered string
}
}
要使用该类,只需设置JsonSerializerOptions
的{{1}},如下所示。
JsonSerializerOptions