Using Json.NET Serialization Attributes with clean classes

Json.NET is a wonderful library for serializing and deserializing JSON in .NET.  It is immensely popular, and is included in the project template for ASP.NET applications.  Often when deserializing JSON, the JSON data does not map to your classes neatly.  You can use serialization attributes to decorate your class members, which will control how Json.NET serializes and deserializes your JSON.  If you use interfaces to define your objects, you can decorate the implemented class while keeping your core definitions clean.

[{"gastypes":["leaded","unleaded"],"pumpcount":"10","sandwichretailer":true,"sodaretailer":true}
,{"gastypes":["leaded","unleaded"],"pumpcount":"6","sandwichretailer":false,"sodaretailer":true}]
  
  public interface IGasStation
    {
        string[] typesOfGas { get; set; }
        string numberOfPumps { get; set; }
    }
  
  public interface IFoodMart
    {
        bool sellsSandiwches { get; set; }
        bool sellsSoda { get; set; }
    }

    public interface IMegaStation : IGasStation, IFoodMart
    {

    }

    public partial class MySuperStation : IMegaStation
    {
        [JsonProperty("gastypes")]
        public string[] typesOfGas { get; set; }
        [JsonProperty("pumpcount")]
        public string numberOfPumps { get; set; }
        [JsonProperty("sandwichretailer")]
        public bool sellsSandiwches { get; set; }
        [JsonProperty("sodaretailer")]
        public bool sellsSoda { get; set; }                 
    }

The decorated MySuperStation class above allows us to deserialize JSON containing different property names by mapping the JsonProperty attribute while keeping our interfaces free of decoration.

 

Leave a Reply