Home > Software design >  Map from another JSON field by condition Newtonsoft.Json
Map from another JSON field by condition Newtonsoft.Json

Time:07-27

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"

CodePudding user response:

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.

CodePudding user response:

Just add a json constructor

Offer price=JsonConvert.DeserializeObject<Offer>(json);

public class Offer
{
    public decimal Price { get; set; }

    [JsonConstructor]
    public Offer(decimal price, decimal cost)
    {
        Price = price == 0 ? cost : price;
    }
     public Offer() {}
}

you don't need to include all properties in the constructor, another properties can remain as it is.

  • Related