Click or drag to resize
Json.NET

JsonObjectAttribute opt-in serialization

 

This sample uses JsonObjectAttribute and MemberSerialization to specify that only properties that have been explicitly specified with JsonPropertyAttribute should be serialized.

Sample
Types
[JsonObject(MemberSerialization.OptIn)]
public class File
{
    // excluded from serialization
    // does not have JsonPropertyAttribute
    public Guid Id { get; set; }

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

    [JsonProperty]
    public int Size { get; set; }
}
Usage
File file = new File
{
    Id = Guid.NewGuid(),
    Name = "ImportantLegalDocuments.docx",
    Size = 50 * 1024
};

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

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