Skip to content

Latest commit

 

History

History
42 lines (35 loc) · 1.48 KB

DataContractAndDataMember.md

File metadata and controls

42 lines (35 loc) · 1.48 KB

DataContract and DataMember Attributes

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