0

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?

martijn
  • 1,417
  • 1
  • 16
  • 26
  • Change type of property type from `double/float/decimal` to `int/long`. – Adnan Umer Aug 15 '16 at 10:15
  • sometimes it gives results in 2 decimal places. ie 1.50. sometimes, it doesn't. It's an old legacy API that im replacing and it has a weird way of working. However I need to guarantee that it will work the same way once I replaced it with C#. – martijn Aug 15 '16 at 10:19
  • Might that helps http://stackoverflow.com/questions/21153381/json-net-serializing-float-double-with-minimal-decimal-places-i-e-no-redundant – Adnan Umer Aug 15 '16 at 10:22

0 Answers0