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"
}
}
这篇关于序列化字典时保留大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:序列化字典时保留大小写
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01