本文介绍了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,其中键将用于属性名称. LowerCase规则不适用于字典键.

例如:

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-小写字母属性和字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 15:05