Serialize object without null field/member in .net web api
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class MemberController : ApiController
{
// GET api/member/5
public Member Get(int id)
{
return new Member()
{
ID = id,
FirstName = "Bruce"
};
}
}
[DataContract]
public class Member
{
[DataMember]
public int ID { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string FirstName { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string LastName { get; set; }
[DataMember(EmitDefaultValue = false)]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? Birthday { get; set; }
}
}