简体   繁体   中英

Set default global json serializer settings

I'm trying to set the global serializer settings like this in my global.asax .

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings = new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    TypeNameHandling = TypeNameHandling.Objects,
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

When serializing object using the following code the global serializer settings are not used?

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent(JsonConvert.SerializeObject(page))
};

Isn't it possible to set the global serializer settings like this or am I missing something?

Setting the JsonConvert.DefaultSettings did the trick.

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    Formatting = Formatting.Indented,
    TypeNameHandling = TypeNameHandling.Objects,
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

Accepted answer did not work for me. In .netcore, I got it working with...

services.AddMvc(c =>
                 {
                 ....
                 }).AddJsonOptions(options => {
                     options.SerializerSettings.Formatting = Formatting.Indented;
                     ....
                 })

只需在您的操作中执行以下操作,以便您可以返回内容协商的响应,并且格式化程序设置也可以生效。

return Request.CreateResponse(HttpStatusCode.OK, page);

You're correct about where to set the serializer. However, that serializer is used when the request to your site is made with a requested content type of JSON. It isn't part of the settings used when calling SerializeObject. You could work around this by exposing the JSON serialization settings defined global.asax via a property.

public static JsonSerializerSettings JsonSerializerSettings
{
    get
    {
        return GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
    }
}

And then use this property to set the serialization settings when doing serialization within your controllers:

return new HttpResponseMessage(HttpStatusCode.OK)
{
    Content = new StringContent(JsonConvert.SerializeObject(page, WebApiApplication.JsonSerializerSettings))
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM