[英]Newtonsoft json Serialize Primitive types WebApi
我有一个使用C#的Web API项目,并且尝试将Json序列化器(Newtonsoft JSON)配置为始终返回包装响应,因为当我的api控制器仅返回布尔值或整数(或其他原始类型)时,我得到了该对象,但我想要类似的东西:
{ d : true }
一个包装的结果,但是没有修改控制器,我看到关于以下内容有很多配置:
config.Formatters.JsonFormatter.SerializerSettings
但是我没有找到提供这种行为的工具。
谢谢!
嗨,我终于解决了从JsonMediaTypeFormatter继承来创建自己的Formatter的问题,如下所示:
config.Formatters.Add(new WrappedJsonMediaTypeFormatter());
public class WrappedJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
public WrappedJsonMediaTypeFormatter()
{
base.SerializerSettings.Culture = new System.Globalization.CultureInfo("en-GB");
base.SerializerSettings.DateFormatString = "dd/MM/yyyy";
}
public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
{
var obj = value;
if (type.IsPrimitive || Object.ReferenceEquals(type, typeof(string)))
obj = new { data = value };
if (Object.ReferenceEquals(value, null))
obj = new { };
return base.WriteToStreamAsync(type, obj, writeStream, content, transportContext);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.