Keep casing when serializing dictionaries(序列化字典时保留大小写)
问题描述
我有一个这样配置的 Web Api 项目:
I have a Web Api project being configured like this:
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
但是,我希望字典键的大小写保持不变.Newtonsoft.Json
中是否有任何属性可以用于一个类来表示我希望在序列化过程中大小写保持不变?
However, I want dictionary keys casing to remain unchanged. is there any attribute in Newtonsoft.Json
I can use to a class to denote that I want casing to remain unchanged during serialization?
public class SomeViewModel
{
public Dictionary<string, string> Data { get; set; }
}
推荐答案
没有属性可以做到这一点,但是你可以通过自定义解析器来做到这一点.
There is not an attribute to do this, but you can do it by customizing the resolver.
我看到您已经在使用 CamelCasePropertyNamesContractResolver
.如果您从中派生一个新的解析器类并覆盖 CreateDictionaryContract()
方法,则可以提供一个不会更改键名的替代 DictionaryKeyResolver
函数.
I see that you are already using a CamelCasePropertyNamesContractResolver
. If you derive a new resolver class from that and override the CreateDictionaryContract()
method, you can provide a substitute DictionaryKeyResolver
function that does not change the key names.
这是您需要的代码:
class CamelCaseExceptDictionaryKeysResolver : CamelCasePropertyNamesContractResolver
{
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
JsonDictionaryContract contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = propertyName => propertyName;
return contract;
}
}
演示:
class Program
{
static void Main(string[] args)
{
Foo foo = new Foo
{
AnIntegerProperty = 42,
HTMLString = "<html></html>",
Dictionary = new Dictionary<string, string>
{
{ "WHIZbang", "1" },
{ "FOO", "2" },
{ "Bar", "3" },
}
};
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CamelCaseExceptDictionaryKeysResolver(),
Formatting = Formatting.Indented
};
string json = JsonConvert.SerializeObject(foo, settings);
Console.WriteLine(json);
}
}
class Foo
{
public int AnIntegerProperty { get; set; }
public string HTMLString { get; set; }
public Dictionary<string, string> Dictionary { get; set; }
}
这是上面的输出.请注意,所有类属性名称都是驼峰式大小写,但字典键保留了它们原来的大小写.
Here is the output from the above. Notice that all of the class property names are camel-cased, but the dictionary keys have retained their original casing.
{
"anIntegerProperty": 42,
"htmlString": "<html></html>",
"dictionary": {
"WHIZbang": "1",
"FOO": "2",
"Bar": "3"
}
}
这篇关于序列化字典时保留大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:序列化字典时保留大小写
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01