1

I'm having an issue with my asp.net REST API that I've created. The JSON string that is returned from a Get request has these trailing whitespaces shown below.

While doing webserches I found this link (Remove trailing spaces from Web API JSON) which shows a solution for removing the trailing whitespaces. The issue is that the link doesn't indicate what files (in the Visual Studio asp.net solution) needed to be modified. I need some help with that, since I'm quite noob-ish at this. Does this fix go into the Global.asax file? If not, where should it go? Is there any other change that I should consider instead of the provided link?

  • I'm not using any custom JSON serializers. I'm using the one that comes stock when you create an asp.net solution in Visual Studio
  • I created this project from a blank asp.net solution (but checked the "Web API" checkbox in the "New ASP.NET Project" dialog box.
  • The provided link shows the solution for a MVC API. I'm not using MVC

What I've got:

{"ID":8,"Site":"EstevanPointCanada","PressureReading":"30.15     ","PressureTrend":"0         "}

What I want:

{"ID":8,"Site":"EstevanPointCanada","PressureReading":"30.15","PressureTrend":"0"}

Any assistance provided would be greatly appreciated.

Community
  • 1
  • 1
M.Harmon
  • 11
  • 1
  • 4
  • 3
    How do you generate this JSON? Trim the values there! – Scoregraphic Sep 21 '16 at 05:06
  • Can you show code where you create that JSON? As @Scoregraphic said you have to trim the values there is a simpliest solution – feeeper Sep 21 '16 at 05:21
  • Found the issue based on the suggestion from Shailesh Kopardekar. The extra whitespaces were due to the extra nchar whitespaces in the DB I was pulling from – M.Harmon Sep 21 '16 at 07:51

3 Answers3

2

Trim the values before generating the JSON or you can apply a foreach on the collection and remove the trailing spaces.

Hope it helps!!

0

In case you are using SQL as a database and the field are of datatype "CHAR", the result will have the trailing spaces when you convert it to JSON.

You need to parse the data converting it to may be string and using "Trim()" function before serializing it to JSON.

If you can show detailed code, it will be helpful to identify the root cause & propose the solution.

  • OP here....this is the answer. I'm pulling these values from a database that has nchar(10) set as the column data type. Kudos for pointing this out – M.Harmon Sep 21 '16 at 06:05
  • I have varchar - and it anyway adds spaces... :( Strange. – Alexander Jun 13 '17 at 10:41
0

Default ASP.NET Web API template contains Json.Net library. So you can implement your own JsonConverter for your type so when your app will serialize instances of that type it will use your custom serializer.

Let's say that your type looks like that:

public class Resp
{
    public int ID { get; set; }
    public string Site { get; set; }
    public string PressureReading { get; set; }
    public int PressureTrend { get; set; }
}

So custom serializer:

public class RespConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Resp);
    }

    public override bool CanRead
    {
        get
        {
            return false;
        }
    }

    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var resp = (Resp)value;
        writer.WriteStartObject();

        writer.WritePropertyName("id");
        writer.WriteValue(resp.ID);

        writer.WritePropertyName("site");
        writer.WriteValue(resp.Site.Trim());

        writer.WritePropertyName("pressureReading");
        writer.WriteValue(resp.PressureReading.Trim());

        writer.WritePropertyName("pressureTrend");
        writer.WriteValue(resp.PressureTrend);

        writer.WriteEndObject();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // the default deserialization works fine, 
        // but otherwise we'd handle that here
        throw new NotImplementedException();
    }
 }

You have to add that converter to your converters in the Register method in the WebApiConfig class and that class will looks so:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // Add custom converter here!
    config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new RespConverter());

}

And your Get method:

public HttpResponseMessage Get(int id)
{
     return Request.CreateResponse<Resp>(HttpStatusCode.Accepted, 
                new Resp { 
                    ID = 1, 
                    Site = "   34.4   ", 
                    PressureReading = "0     ", 
                    PressureTrend = 42 });
}

will return: {"id":1,"site":"34.4","pressureReading":"0","pressureTrend":42}

feeeper
  • 2,865
  • 4
  • 28
  • 42
  • Should be something simpler, like an option: "trim char data". Imagine if you have hundreds of properties and hundreds of objects? – Alexander Jun 13 '17 at 10:40
  • @Alexander I think you can use reflection for that: 1. `CanConvert` should return `true` for all your need-to-serialize-classes; 2. get all public properties in the `WriteJson` method and serialize them – feeeper Jun 14 '17 at 11:37