防止属性在 Web API 中被序列化 [英] prevent property from being serialized in web API
问题描述
我正在使用 MVC 4 Web API 和 asp.net Web Forms 4.0 来构建休息 API.效果很好:
I'm using an MVC 4 web API and asp.net web forms 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;
}
现在我需要防止一些属性被序列化.我知道我可以在列表上使用一些 LINQ 并只获取我需要的属性,通常这是一个很好的方法,但在目前的场景中 something
对象太复杂了,我需要一个不同的集合不同方法中的属性,因此在运行时更容易标记要忽略的每个属性.
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 generally 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 runtime, 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, 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; }
}
更多理解,可以阅读官方文章.
这篇关于防止属性在 Web API 中被序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!