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

我想要使序列化出来的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:

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

Usage:

var settings = new JsonSerializerSettings();
settings.ContractResolver = new LowercaseContractResolver();
var json = JsonConvert.SerializeObject(authority, Formatting.Indented, settings);

Wil result in:

{"username":"Mark","apitoken":"xyzABC1234"}

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

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:

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 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券