Search code examples
c#json.netjson.net

Map from another JSON field by condition Newtonsoft.Json


I have json

{
  price: 0.0
  cost: 12.5
}

And model

public class Offer
{
    [JsonProperty("price")]
    public decimal Price { get; set; }
}

I want to map data from JSON property "cost" when price = 0.0
But if price != 0.0, map from "price"


Solution

  • A simple approach is to use a readonly property for this:

    public class Offer
    {
        [JsonProperty("price")]
        public decimal Price { get; set; }
    
        [JsonProperty("cost")]
        public decimal Cost { get; set; }
    
        [JsonIgnore]
        public decimal PriceOrCost  => Price == 0m ? Cost : Price;
    }
    

    Both properties are deserialized from JSON and you have an additional one that contains the condition. This property is marked with a JsonIgnore property in order not to write it to JSON when serializing.