Search code examples
c#json.netdefault-value

Custom DefaultValue depending on the PC using Newtonsoft


I have a JSON config value that could be different based on the number of processors, the memory size, the OS and so on.

The value itself can be calculated fairly easily at runtime, so I don't expect my users to have an entry for it in their own config.
But in some edge cases, the user could have their own value, (for test or load and so on).

I can set a default value, but that 'default' will not be the same for all machines:

...

[DefaultValue(8)]
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Populate)]
public int EventsPerProcessor { get; protected set; }

...

Is there a way of knowing if the value was missing or not so I can calculate the correct 'default' value?

Or something like [DefaultValue(MyCustomFunction(...) )]?

NB: Of course, I could set my default value to 0, (or even -ve), but then I would prefer to not assume that the user entered that value or not.


Solution

  • Since the only effect of DefaultValueHandling.Populate is that

    Members with a default value but no JSON will be set to their default value when deserializing.

    You could remove [DefaultValue(...)] and DefaultValueHandling entirely and, instead, initialize EventsPerProcessor in the class constructor:

    public class RootObject
    {
        static int CalculateDefaultEventsPerProcessor()
        {
            // Replace with calculated value
            return 12;
        }
    
        public RootObject()
        {
            EventsPerProcessor = CalculateDefaultEventsPerProcessor();
        }
    
        [JsonProperty]
        public int EventsPerProcessor { get; protected set; }
    }
    

    If "EventsPerProcessor" is not present in the JSON, the value calculated in the constructor will remain unchanged.

    Note that, since EventsPerProcessor has a protected setter, it is still necessary to apply [JsonProperty].

    Sample fiddle here.