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 - 小写属性和字典
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
