Remove trailing spaces from Web API JSON

2019-07-30 01:11发布

I am creating a Web API application that wraps up some legacy systems underneath which have databases that using nchar instead of nvarchar for all string columns.

This obviously give me the issue that all strings that come from the database have a load of white space to pad them out to the field length at the end.

As I am returning JSON, I would like to make sure that the JSON is minified as much as possible and trim the strings. What I don't want to have to do is perform a TrimEnd() on all of my strings manually in the code.

To achieve this, I was thinking that I could do this in the JSON serialiser being used by WebAPI to output the object. I have tried looking around in

GlobalConfiguration.Configuration.Formatters.JsonFormatter

to see if I can find a way to do this but I am struggling to find a viable option.

Has anyone tried to do this before and how have they managed to do it without a manual loop through the fields and without creating a significant performance overhead?

1条回答
Melony?
2楼-- · 2019-07-30 01:27

You should try using the Newtonsoft.Json serializer. You can configure it to remove all unnecessary white spaces by setting the formatting to Formatting.None:

var jsonNetSettings = new JsonSerializerSettings
{
    Formatting = Formatting.None,
};

Then get your jsonFormatter object from GlobalConfiguration.Configuration.Formatters and assign the new settings:

jsonFormatter.SerializerSettings = jsonNetSettings;
查看更多
登录 后发表回答