ASP.Net Core 2.2 - separate serializer settings for input and output

前端 未结 2 1164
予麋鹿
予麋鹿 2021-01-24 19:40

ASP.Net Core 2.2 allows to set serializer settings using MvcJsonOptions.SerializerSettings property. The problem is that it affects both input and output. Is there

相关标签:
2条回答
  • 2021-01-24 20:21

    Finally found this workaround: https://github.com/aspnet/Mvc/issues/4562#issuecomment-226100352

    public class CustomSerializerSettingsSetup : IConfigureOptions<MvcOptions>
    {
        private readonly ILoggerFactory _loggerFactory;
        private readonly ArrayPool<char> _charPool;
        private readonly ObjectPoolProvider _objectPoolProvider;
    
        public CustomSerializerSettingsSetup(
            ILoggerFactory loggerFactory,
            ArrayPool<char> charPool,
            ObjectPoolProvider objectPoolProvider)
        {
            _loggerFactory = loggerFactory;
            _charPool = charPool;
            _objectPoolProvider = objectPoolProvider;
        }
    
        public void Configure(MvcOptions options)
        {
            options.OutputFormatters.RemoveType<JsonOutputFormatter>();
            options.InputFormatters.RemoveType<JsonInputFormatter>();
            options.InputFormatters.RemoveType<JsonPatchInputFormatter>();
    
            var outputSettings = new JsonSerializerSettings();
            options.OutputFormatters.Add(new JsonOutputFormatter(outputSettings, _charPool));
    
            var inputSettings = new JsonSerializerSettings();
            var jsonInputLogger = _loggerFactory.CreateLogger<JsonInputFormatter>();
            options.InputFormatters.Add(new JsonInputFormatter(
                jsonInputLogger,
                inputSettings,
                _charPool,
                _objectPoolProvider));
    
            var jsonInputPatchLogger = _loggerFactory.CreateLogger<JsonPatchInputFormatter>();
            options.InputFormatters.Add(new JsonPatchInputFormatter(
                jsonInputPatchLogger,
                inputSettings,
                _charPool,
                _objectPoolProvider));
        }
    }
    

    and

    services.TryAddEnumerable(
        ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, CustomSerializerSettingsSetup>());
    

    in service provider configuration

    0 讨论(0)
  • 2021-01-24 20:29

    I would use JsonSerializerSettings class from Newtonsoft.Json to define two instances mySerializeSetting and myDeserializeSettings.

    using Newtonsoft.Json;
    using Microsoft.Rest.Serialization;
    
    string requestContent = SafeJsonConvert.SerializeObject(value, mySerializationSettings);
    

    To deserialize:

    var result = SafeJsonConvert.DeserializeObject<myclass>(input, myDeserializeSettings);
    

    To see how to set up serialization settings see https://www.newtonsoft.com/json/help/html/SerializationSettings.htm

    0 讨论(0)
提交回复
热议问题