Serialize object without null field/member to xml/json
class Program
{
static void Main(string[] args)
{
var m = new Member()
{
ID = 3,
FirstName = "Bruce"
};
var dto = new MemberDTO()
{
ID = 3,
FirstName = "Bruce"
};
// Serialize to xml format
var xs = new System.Xml.Serialization.XmlSerializer(typeof(Member));
var sw = new System.IO.StringWriter();
xs.Serialize(sw, m);
Console.WriteLine("Serialize object to xml");
Console.WriteLine(sw);
// Serialize to xml format without null value
xs = new System.Xml.Serialization.XmlSerializer(typeof(MemberDTO));
sw = new System.IO.StringWriter();
xs.Serialize(sw, dto);
Console.WriteLine("Serialize dto-object to xml");
Console.WriteLine(sw);
Console.WriteLine("Serialize object to json");
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(m));
Console.WriteLine("Serialize dto-object to json");
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(dto));
Console.Read();
}
}
public class Member
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? Birthday { get; set; }
}
public class MemberDTO
{
public int ID { get; set; }
[Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string FirstName { get; set; }
[Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public string LastName { get; set; }
[Newtonsoft.Json.JsonProperty(NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
public DateTime? Birthday { get; set; }
#region
public bool ShouldSerializeFirstName()
{
return !string.IsNullOrWhiteSpace(FirstName);
}
public bool ShouldSerializeLastName()
{
return !string.IsNullOrWhiteSpace(LastName);
}
public bool ShouldSerializeBirthday()
{
return Birthday.HasValue;
}
#endregion
}
Result:
Serialize object to xml
<?xml version="1.0" encoding="utf-16"?>
<Member xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>3</ID>
<FirstName>Bruce</FirstName>
<Birthday xsi:nil="true" />
</Member>
Serialize dto-object to xml
<?xml version="1.0" encoding="utf-16"?>
<MemberDTO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ID>3</ID>
<FirstName>Bruce</FirstName>
</MemberDTO>
Serialize object to json
{"ID":3,"FirstName":"Bruce","LastName":null,"Birthday":null}
Serialize dto-object to json
{"ID":3,"FirstName":"Bruce"}