0

I have a FilterDto class I use to send filter information to my client application. For instance:

public class FilterDto
{
    public string Code { get; set; } = "Default code";
    public string Description { get; set; }
}

This is serialized like:

[
    {
        field: 'Code',
        type: 'text',
        defaultValue: 'Default code'
    },
    {
        field: 'Description ',
        type: 'text',
        defaultValue: null
    }
]

So in my client I can render two input text for the given fields. And when the user filters the JSON sent back is something like:

{
    Code: 'code to filter',
    Description: 'description to filter'
}

And I desserialize it like:

var filter = JsonConvert.DeserializeObject(json, typeof(FilterDto));
Console.WriteLine(filter.Code); // code to filter

The problem is, if the user decides to erase the default value for code, in the above example, I will have the JSON:

{
    Description: 'description to filter'
}

And when desserializing I will have:

var filter = JsonConvert.DeserializeObject(json, typeof(FilterDto));
Console.WriteLine(filter.Code); // Default code

Is there a way to set the Code to null instead of its default value when it is missing from the JSON?

Thanks

João Menighin
  • 3,083
  • 6
  • 38
  • 80

2 Answers2

2

Try this:

        public class FilterDto
        {
            private const string DefaultValue = "Default code";

            [OnDeserialized]
            internal void OnDeserializedMethod(StreamingContext context)
            {
                if (Code == DefaultValue)
                {
                    Code = null; //set to null or string.empty
                }
            }

            public string Code { get; set; } = DefaultValue;
            public string Description { get; set; }
        }
auburg
  • 1,373
  • 2
  • 12
  • 22
  • This works but I was expecting something more generic... Without having to write that logic for every `FilterDto` I have... Currently I'm using some reflection to set the values to default if they are not present in the json... – João Menighin Apr 29 '19 at 15:50
  • Have a look into this link: https://stackoverflow.com/questions/32908592/add-a-custom-attribute-to-json-net – auburg Apr 29 '19 at 16:06
0

i believe, what you are looking already explained here

.

in addition, if property is not exists you might add

[JsonProperty(PropertyName ="defaultValue", NullValueHandling = NullValueHandling.Include, DefaultValueHandling = DefaultValueHandling.Populate)]

also, this article will give you idea how to cover null value: here

Power Mouse
  • 727
  • 6
  • 16