1

a C# ASP.NET Webform site using WebAPI

I have a petapoco class that has 50 properties on it, but for certain WebAPI methods I would like to filter what properties are serialized and sent to the client in the HttpResponseMessage (to reduce the payload).

For Example let say I have the following class properties in a class:

ID, FirstName, LastName, Address, City, State, Zip, DOB    

I need some WebApi methods to serialize every property, but maybe another method I only want to return

ID, FirstName, LastName

Is there a built in way to handle this? If not, what's the best way to build out something to handle this?

Edit: I'm looking for a way to do this without modifying the class

Brad Bamford
  • 3,783
  • 3
  • 22
  • 30
  • If you are using Json, you can take a look at the following which describes about creating a custom contract resolver for this: http://james.newtonking.com/json/help/html/ConditionalProperties.htm – Kiran Dec 18 '13 at 19:11

2 Answers2

0

You should be able to create ShouldSerialize methods for each property.

Xml serialization - Hide null values

Gives you the ability to dynamically decide which fields get serialized. Don't worry that the link says XML, should work for JSON serialization too.

Community
  • 1
  • 1
ryan1234
  • 7,237
  • 6
  • 25
  • 36
  • ShouldSerialize would work, but I'm looking for a way to do this without modifying the serializable class or having to create a partial class. – Brad Bamford Dec 20 '13 at 13:54
0

uses the JsonIgnoreAttribute to exclude a property from serialization.

for example in model.cs:

public class Account
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [JsonIgnore]
    public string Address { get; set; }
    [JsonIgnore]
    public string City { get; set; }
    [JsonIgnore]
    public string State { get; set; }
.
.
.
}