M.Harmon
M.Harmon

Reputation: 11

Remove Trailing Whitespace from JSON (ASP.NET API)

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?

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.

Upvotes: 1

Views: 2771

Answers (3)

feeeper
feeeper

Reputation: 3017

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}

Upvotes: 0

Abhishek K. Upadhyay
Abhishek K. Upadhyay

Reputation: 1032

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

Hope it helps!!

Upvotes: 2

Shailesh Kopardekar
Shailesh Kopardekar

Reputation: 91

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.

Upvotes: 0

Related Questions