Newtonsoft JsonSerializer - Lower case properties and dictionary(Newtonsoft JsonSerializer - 小写属性和字典)
问题描述
我正在使用 json.net(Newtonsoft 的 JsonSerializer).我需要自定义序列化以满足以下要求:
I'm using json.net (Newtonsoft's JsonSerializer). I need to customize serialization in order to meet following requirements:
- 属性名称必须以小写字母开头.
- 字典必须序列化为 jsonp,其中的键将用于属性名称.小写规则不适用于字典键.
例如:
var product = new Product();
procuct.Name = "Product1";
product.Items = new Dictionary<string, Item>();
product.Items.Add("Item1", new Item { Description="Lorem Ipsum" });
必须序列化为:
{
name: "Product1",
items : {
"Item1": {
description : "Lorem Ipsum"
}
}
}
注意属性 Name 序列化为name",但键 Item1 序列化为Item1";
notice that property Name serializes into "name", but key Item1 serializes into "Item1";
我尝试创建 CustomJsonWriter 来序列化属性名称,但它也会更改字典键.
I have tried to create CustomJsonWriter to serialize property names, but it changes also dicionary keys.
public class CustomJsonWriter : JsonTextWriter
{
public CustomJsonWriter(TextWriter writer) : base(writer)
{
}
public override void WritePropertyName(string name, bool escape)
{
if (name != "$type")
{
name = name.ToCamelCase();
}
base.WritePropertyName(name, escape);
}
}
推荐答案
您可以尝试使用 CamelCasePropertyNamesContractResolver
.
var serializerSettings = new JsonSerializerSettings();
serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
var json = JsonConvert.SerializeObject(product, serializerSettings);
我只是不确定它将如何处理字典键,而且我现在没有时间尝试它.如果它不能正确处理密钥,那么未来仍然值得牢记,而不是编写自己的自定义 JSON 编写器.
I'm just not sure how it'll handle the dictionary keys and I don't have time right this second to try it. If it doesn't handle the keys correctly it's still worth keeping in mind for the future rather than writing your own custom JSON writer.
这篇关于Newtonsoft JsonSerializer - 小写属性和字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Newtonsoft JsonSerializer - 小写属性和字典
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01