Newtonsoft JsonSerializer - 小写属性和字典

时间:2023-04-25
本文介绍了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:

  1. 属性名称必须以小写字母开头.
  2. 字典必须序列化为 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 - 小写属性和字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:从 Json 字符串中提取数据 下一篇:反序列化 Newtonsoft.Json 中的自定义异常

相关文章