如何更改Json.NET的序列化规则

2019-09-04 16:31:00 浏览数 (1)

我想要使序列化出来的JSON都是小写,可以通过建立 LowercaseContractResolver:DefaultContractResolver

来实现, 创建Custom ContractResolver可以对很多东西进行更改,可以自定义规则。。。 如果你只要针对某个的话,可以用 JsonProperty 或者使用CustomJsonConverter: JsonConverter。。

改变规则:

http://stackoverflow.com/questions/6288660/net-ensuring-json-keys-are-lowercase

http://stackoverflow.com/questions/12501805/how-to-set-json-net-contractserializer-for-a-certain-specific-type-instead-of-gl

http://stackoverflow.com/questions/25183710/serialize-json-property-name

CustomJsonConverter:

http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/

DATE TIME: http://cgeers.com/2011/09/25/writing-a-custom-json-net-datetime-converter/

You can create a custom contract resolver for this. The following contract resolver will convert all keys to lowercase:

代码语言:javascript复制
public class LowercaseContractResolver : DefaultContractResolver
{
    protected override string ResolvePropertyName(string propertyName)
    {
        return propertyName.ToLower();
    }
}

Usage:

代码语言:javascript复制
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);

Wil result in:

代码语言:javascript复制
{"username":"Mark","apitoken":"xyzABC1234"}

If you always want to serialize using the LowercaseContractResolver, consider wrapping it in a class to avoid repeating yourself:

代码语言:javascript复制
public class LowercaseJsonSerializer
{
    private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        ContractResolver = new LowercaseContractResolver()
    };

    public static string SerializeObject(object o)
    {
        return JsonConvert.SerializeObject(o, Formatting.Indented, Settings);
    }

    public class LowercaseContractResolver : DefaultContractResolver
    {
        protected override string ResolvePropertyName(string propertyName)
        {
            return propertyName.ToLower();
        }
    }
}

Which can be used like this:

代码语言:javascript复制
var json = LowercaseJsonSerializer.SerializeObject(new { Foo = "bar" });
// { "foo": "bar" }

ASP.NET MVC4 / WebAPI

If you are using ASP.NET MVC4 / WebAPI, you can use a CamelCasePropertyNamesContractResolverfrom Newtonsoft.Json library which included by default.

0 人点赞