Alexandros Mor
Alexandros Mor

Reputation: 127

Decimal properties are serialized even are not populated

I had to generate some classes from an xsd file. The classes and properties are generated correct with xml serialization annotation. The problem is that the decimal properties of a class are serialized with Newtonsoft.Json even are not populated. I would like to serialize only the decimal properties that are properly populated. Amount is part of SaleMessage For example:

class Amount
{
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal RequestedAmount;

[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal CashBackAmount;

[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal TipAmount;
}

//Usage
var amount = new Amount()
{
 RequestedAmount = 12.0
}

Using this structure it will always serialize all the properties like this {"RequestedAmount":12.0,"CashBackAmount":0.0,"TipAmount":0.0} Which is not the expected behaviour. The question is how can I modify the serialization to not parse the not set properties

 static string Serialize(SaleMessage saleMessage)
        {
            var serialize= JsonConvert.SerializeObject(saleToPoiMessage,
                new StringEnumConverter(),
                new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat });
            return serialize;
        }

Any help is appreciated :)

Upvotes: 0

Views: 688

Answers (3)

Alexandros Mor
Alexandros Mor

Reputation: 127

In my case I changed the primitive types to nullable.

public decimal? CashBackAmount {get; set;}

This worked for me. I prefer the @Brian Rogers answer. :)

Upvotes: 0

Brian Rogers
Brian Rogers

Reputation: 129837

You can set the DefaultValueHandling setting to Ignore to suppress serialization of values that are equal to their default value.

var settings = new JsonSerializerSettings
{
    Converters = new List<JsonConverter> 
    { 
        new StringEnumConverter(),
        new IsoDateTimeConverter() { DateTimeFormat = DateTimeFormat } 
    },
    DefaultValueHandling = DefaultValueHandling.Ignore
};

var json = JsonConvert.SerializeObject(saleMessage, settings);

Fiddle: https://dotnetfiddle.net/o32k0U

Upvotes: 1

Robin Gautam
Robin Gautam

Reputation: 23

Since it's of type decimal primitive it will have some value by default. I think you need to implement the serializer utility Newtonsoft.Json uses - on your own. Where you will not include the decimal values of 0.0 (if this suits the business logic).

Another option is not to use the primitive class and then set up the property of removing null values while serializing. I believe you can set up this config parameter in Newtonsoft.

Check this: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

Upvotes: 0

Related Questions