2

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!

3
  • What are you getting at the moment? Commented Nov 7, 2013 at 15:42
  • Just "true" or the numbers Commented Nov 7, 2013 at 16:21
  • Anyone? Did OP get a solution to this? E.g. returning a decimal of 0.54 gives exactly that, instead of a wrapped response like { "Result": 0.54 } Commented Mar 31, 2014 at 5:44

1 Answer 1

1

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);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.