去除的Json空的属性,在MVC网页API 4 Beta版 [英] Removing Null Properties from Json in MVC Web Api 4 Beta
问题描述
我的对象序列化和返回从我的web服务的JSON。不过,我想省略JSON序列化空的属性。有没有办法做到这一点?我使用的网页API MVC 4测试版。
I'm serializing objects and returning as json from my web service. However, I'm trying to omit null properties from serialized json. Is there a way to do this? I'm using Web Api MVC 4 beta.
推荐答案
目前的ASP.NET Web API(<一个href=\"http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx\">there计划以改变它的最终发布使用Json.Net)使用 DataContractJsonSerializer 默认序列化JSON。
The ASP.NET Web API currently (there are plans to change it for the final release to use Json.Net) uses DataContractJsonSerializer by default to serialize JSON.
所以,你可以用标准的DataContract控制序列化过程中/的DataMember属性。要跳过空的属性,您可以设置<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.emitdefaultvalue.aspx\">EmitDefaultValue为false。
So you can control the serialization process with the standard DataContract/DataMember attributes. To skip null properties you can set the EmitDefaultValue to false.
[DataContract]
public class MyObjet
{
[DataMember(EmitDefaultValue = false)]
public string Prop1 { get; set; }
[DataMember(EmitDefaultValue = false)]
public string Prop2 { get; set; }
}
如果您想对JSON响应如何序列化,你可以使用 WebAPIContrib 包,其中包含使用格式化的更多控制< A HREF =HTTP://json.$c$cplex.com/> Json.Net 或内置<一href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\">JavaScriptSeralizer.
If you want to have more control on how the JSON responses are serialized you can use the WebAPIContrib package which contains formatters using Json.Net or the built in JavaScriptSeralizer.
这篇关于去除的Json空的属性,在MVC网页API 4 Beta版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!