I am using a Aps.Net Web Api 2.0 project in which I return database data in Json format. I am replacing an existing JAVA application in C#. So far it's going fine except that my web api formats the return data. This would be bad because I want the return data to be identical to the existing return data.
My webapi controller class:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "foo/bar/{controller}"
);
// Sets default output to Json for most requests
// http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// supress null values, format date
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
DateFormatString = "yyyy-MM-dd"
};
}
}
given object:
dummyobject foobar = new dummyobject
{
stringval = "string with spaces at end ",
zerodecimal = 0M
};
My current json response string:
{
"stringval":"string with spaces at end ",
"zerodecimal":0.0
}
the json response I need:
{
"stringval":"string with spaces at end ";
"zerodecimal":0
}
UPDATE: So i discovered that the default api Json serializer is the Newtonsoft.Json library. It has a bunch of settings but none of which I can use to serialize the way i want to serialize. However the JavaScriptSerializer does serialize correctly:
JavaScriptSerializer Foo= new JavaScriptSerializer();
StringBuilder Bar = new StringBuilder();
Foo.Serialize(foobar, Bar);
return builder.ToString();
So to update my question, how do I change the default web api serializer? From NewtonSoft to the JavaScriptSerializer?