DataContract and DataMember Attributes

April 6, 2024 ยท View on GitHub

This sample shows how .NET Framework attributes such as DataContractAttribute, DataMemberAttribute and NonSerializedAttribute can be used with Json.NET instead of Json.NET's own attributes.

[DataContract]
public class File
{
    // excluded from serialization
    // does not have DataMemberAttribute
    public Guid Id { get; set; }

    [DataMember] public string Name { get; set; }

    [DataMember] public int Size { get; set; }
}

snippet source | anchor

var file = new File
{
    Id = Guid.NewGuid(),
    Name = "ImportantLegalDocuments.docx",
    Size = 50 * 1024
};

var json = JsonConvert.SerializeObject(file, Formatting.Indented);

Console.WriteLine(json);
// {
//   "Name": "ImportantLegalDocuments.docx",
//   "Size": 51200
// }

snippet source | anchor