简体   繁体   中英

Newtonsoft json Serialize Primitive types WebApi

I have a Web API project with C# and I am trying to configure the Json Serializer (Newtonsoft JSON) to return always a wrapped response, because when my api controller just returns a Boolean or a integer (or other primitive types), I just get the object but I want something like:

{ d : true } 

a wrapped result but without modifying the controller, i saw that there are a lot of configuration stuff on:

config.Formatters.JsonFormatter.SerializerSettings

but i don´t found the one that provides this behavior.

Thanks!

Hi finally I solved creating my own Formatter inheriting from JsonMediaTypeFormatter, like this:

config.Formatters.Add(new WrappedJsonMediaTypeFormatter());

public class WrappedJsonMediaTypeFormatter : JsonMediaTypeFormatter
{

        public WrappedJsonMediaTypeFormatter() 
        {
            base.SerializerSettings.Culture = new System.Globalization.CultureInfo("en-GB");
            base.SerializerSettings.DateFormatString = "dd/MM/yyyy";
        }

        public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            var obj = value;
            if (type.IsPrimitive || Object.ReferenceEquals(type, typeof(string)))
                obj = new { data = value };

            if (Object.ReferenceEquals(value, null))
                obj = new { };

            return base.WriteToStreamAsync(type, obj, writeStream, content, transportContext);
        }
    }

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