Prevent Property from Being Serialized in Web API

Exclude property from json serialization in ApiController

Be aware that JSON serialization is changing in Web API.

In the beta release, Web API used DataContractJsonSerializer to serialize JSON. However, this has changed; the latest version of Web API uses json.net by default, although you can override this and use DataContractJsonSerializer instead.

With DataContractJsonSerializer, you can use [DataContract] attributes to control the serialization. I'm stil not very familiar with json.net, so I don't know how it controls serialization.

C# WebApi 2. JSON Serialization. Exclude property from partial classes

I think you are looking for [JsonIgnore] for the Json serializer or [IgnoreDataMember] for the default XML serializer.

But I can see in your code that you are using [DataContract], you can definitely do this also:

[DataContract]
public class YourClass
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Prop1 { get; set; }

//ignored
public string IgnoredProp { get;set; }
}

Prevent class property from being serialized

try [JsonIgnore] or [IgnoreDataMember] attribute, that will help you.

JsonIgnore attribute keeps serializing properties in ASP.NET Core 3

[JsonIgnore] is an JSON.NET attribute and won't be used by the new System.Text.Json serializer.

Since your application is an ASP.NET Core 3.0 System.Text.Json will be used by default. If you want to continue to consume the JSON.NET annotations, you have to use JSON.NET in ASP.NET Core 3

It's as easy as adding .AddNewtonsoftJson() to your MVC or WebApi Builder

services.AddMvc()
.AddNewtonsoftJson();

or

services.AddControllers()
.AddNewtonsoftJson();

for WebAPI-esque applications.

How to exclude property from Json Serialization

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }

// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }

// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}

Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details



Related Topics



Leave a reply



Submit