在网页API被序列化prevent财产 [英] prevent property from being serialized in web api
问题描述
我使用MVC 4个Web API和asp.net web表单4.0构建一个REST API。它的工作的伟大:
I'm using a mvc 4 web api and asp.net webforms 4.0 to build a rest api. It's working great:
[HttpGet]
public HttpResponseMessage Me(string hash)
{
HttpResponseMessage httpResponseMessage;
List<Something> somethings = ...
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK,
new { result = true, somethings = somethings });
return httpResponseMessage;
}
现在我需要prevent某些属性被序列化。我知道我可以使用一些LINQ在列表并只获得我所需要的属性,generaly这是一个很好的方法,但在present方案中的的东西
对象太复杂了,我需要一个不同的集不同的方法特性,所以它更容易标记,在运行时,被忽略每个属性。
Now I need to prevent some properties to be serialized. I know I can use some linq over the list and get only the properties I need, and generaly it's a good approach, but in the present scenario the something
object is too complex, and I need a different set of properties in different methods, so it's easier to mark, at run time, each property to be ignored.
有没有办法做到这一点?
Is there a way to do that?
推荐答案
的ASP.NET Web API使用 的Json .NET
为默认格式,因此,如果您的应用程序仅仅只使用JSON作为数据格式,可以使用 [JsonIgnore]
忽略属性序列化:
ASP.NET Web API uses Json.Net
as default formatter, so if your application just only uses JSON as data format, you can use [JsonIgnore]
to ignore property for serialization:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
public List<Something> Somethings { get; set; }
}
但遗憾的是这种方式不支持XML格式。所以,如果您的应用程序的必须的支持XML格式更多(或只支持XML),而不是使用 Json.Net
,你应该使用 [DataContract]
同时支持JSON和XML:
But, sadly this way does not support XML format. So, in case your application has to support XML format more (or only support XML), instead of using Json.Net
, you should use [DataContract]
which supports both JSON and XML:
[DataContract]
public class Foo
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
//Ignore by default
public List<Something> Somethings { get; set; }
}
有关更多的了解,您可以阅读<一href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization\">official文章。
For more understanding, you can read the official article.
这篇关于在网页API被序列化prevent财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!