Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8545403
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T12:47:01+00:00 2026-06-11T12:47:01+00:00

I am trying to find the best way to conditionally include and remove properties

  • 0

I am trying to find the best way to conditionally include and remove properties from my datacontract serialization in my .net WebApi project. In my Api, I want to allow users to specify the fields that they want returned.

For example, assume I want my API to return an instance of the following class.

public class Car
{
    public int Id { get; set; }
    public string Year { get; set; }
    public string Make { get; set; }
    public string Model { get; set; }
    public string Color { get; set; }
}

But instead of requesting the entire object, the API call wants the Id and Make field only. So the return JSON would be

 { "Id": 12345, "Make": "Ford"}

instead of the entire object.

Is there a way with the DataContract Serializer that I can conditionally add and remove properties from my return object?

**EDIT
I have looked at the IgnoreDefault property, and I don’t believe it will do exactly what I need. The problem is that I want to include and exclude properties based on an api request, not necessarily on whether or not they have data.

Is there some way to hook into the deserialization process and skip certain properties? Can I do some kind of custom contract?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T12:47:02+00:00Added an answer on June 11, 2026 at 12:47 pm

    If you’re using the DataContractSerializer (or, in this case, the DataContractJsonSerializer), you can use the DataMember(EmitDefaultValue = false)] decoration in your class. This way, you can set the properties which you don’t want serialized to their default values (i.e., null for strings, 0 for ints and so on), and they won’t be.

    If you’re using the ASP.NET Web API, then you should be aware that the default JSON serializer isn’t the DataContractJsonSerializer (DCJS), but JSON.NET instead. So unless you explicitly configure your JsonMediaTypeFormatter to use DCJS, you need another attribute to get the same behavior (JsonProperty, and its DefaultValueHandling property).

    The code below only serializes the two members which were assigned in this Car object, using both serializers. Notice that you can remove one of the attributes if you’re only going to use one of them.

    public class StackOverflow_12465285
    {
        [DataContract]
        public class Car
        {
            private int savedId;
            private string savedYear;
            private string savedMake;
            private string savedModel;
            private string savedColor;
    
            [DataMember(EmitDefaultValue = false)]
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
            public int Id { get; set; }
            [DataMember(EmitDefaultValue = false)]
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
            public string Year { get; set; }
            [DataMember(EmitDefaultValue = false)]
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
            public string Make { get; set; }
            [DataMember(EmitDefaultValue = false)]
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
            public string Model { get; set; }
            [DataMember(EmitDefaultValue = false)]
            [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
            public string Color { get; set; }
    
            [OnSerializing]
            void OnSerializing(StreamingContext ctx)
            {
                this.savedId = this.Id;
                this.savedYear = this.Year;
                this.savedMake = this.Make;
                this.savedModel = this.Model;
                this.savedColor = this.Color;
    
                // Logic to determine which ones to serialize, let's say I only want Id, Make; so make all others default.
                this.Color = default(string);
                this.Model = default(string);
                this.Year = default(string);
            }
    
            [OnSerialized]
            void OnSerialized(StreamingContext ctx)
            {
                this.Id = this.savedId;
                this.Year = this.savedYear;
                this.Make = this.savedMake;
                this.Model = this.savedModel;
                this.Color = this.savedColor;
            }
        }
    
        public static void Test()
        {
            Car car = new Car { Id = 12345, Make = "Ford", Model = "Focus", Color = "Red", Year = "2010" };
            JsonSerializer js = new JsonSerializer();
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            js.Serialize(sw, car);
            Console.WriteLine("Using JSON.NET: {0}", sb.ToString());
    
            MemoryStream ms = new MemoryStream();
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Car));
            dcjs.WriteObject(ms, car);
            Console.WriteLine("Using DCJS: {0}", Encoding.UTF8.GetString(ms.ToArray()));
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying find the best way to remove nonnumerical data from a varchar in
I'm trying to find the best way to load a source table from MySQL
I'm using ASP.NET MVC with Razor syntax. I'm trying to find the best way
I'm trying to find the best way to retrieve fields from a table, depending
I'm trying to find the best way to deal with the way that ASP.NET
Trying to find the best way of create an overlap/overlay layer to fill the
I am trying to find the best way to implement Model using Zend Framework
I'm trying to find the best way to design my application and precisely my
I'm trying to find the best way (in code) to determine the final destination
I am trying to find the best way to build a dynamic linq query

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.