从Web API JSON删除尾随空格 [英] Remove trailing spaces from Web API JSON

查看:179
本文介绍了从Web API JSON删除尾随空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个Web API应用程序,该应用程序包装了一些旧系统,这些旧系统的数据库在所有字符串列中使用nchar而不是nvarchar.

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.

当我返回JSON时,我想确保尽可能缩小JSON并修剪字符串.我不需要做的是在代码中手动对所有字符串执行TrimEnd().

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.

要实现这一点,我想我可以在WebAPI用来输出对象的JSON序列化器中做到这一点.我尝试在

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?

推荐答案

您应该尝试使用Newtonsoft.Json序列化程序.您可以通过将格式设置为Formatting.None来配置它以删除所有不必要的空格

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,
};

然后从GlobalConfiguration.Configuration.Formatters中获取jsonFormatter对象并分配新设置:

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

jsonFormatter.SerializerSettings = jsonNetSettings;

这篇关于从Web API JSON删除尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆