0

I have a public class with some public immutable properties (only get;). It also has a custom constructor, which takes one additional parameter, required not for the setting of a property, but only for the calculations. I think, because of that, this class cannot be deserialized properly via Newtonsoft Json. Other classes with only corresponding input parameters to the properties work fine.

So, this class deserializes itself not properly, returning zeros. It has additional parameter 'value' which is not related to any property, and just used for a calcualtions and presenting the data.

public class DurationData
    {
        public DateTime Start { get; }

        public int Index { get; }

        public double ActivityDurationInHours { get; }

        public string Activetime { get; }

        public ShiftDurationData(DateTime start, int index, TimeSpan value )
        {
            Start = start;
            Index = shiftIndex;                 
            ActivityDurationInHours = Math.Round(value.TotalHours, 1);
            Activetime = $"{(int)value.TotalHours:d2}:{value.Minutes:D2}:{value.Seconds:D2}";
        }        
    }

if I set the mock of this like below or just with mutable properties (get;set) and without a constructor it deserializes itself properly.

public class DurationData { public DateTime Start { get; }

        public int Index { get; }

        public double ActivityDurationInHours { get; }

        public string Activetime { get; }

        public ShiftDurationData(DateTime start, int index, double activityDurationInHours, string activeTime)
        {
            Start = start;
            Index = shiftIndex;                 
            ActivityDurationInHours = activityDurationInHours
            ActiveTime = activetime ?? throw new ArgumentNullException(nameof(activeTime))
        }        
    }

But I don't wan't to create additional mock class and would like to work with original. How to do this properly

E Markov
  • 1
  • 1
  • Are you able to modify the `DurationData` class by adding Json.NET [serialization attributes](https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm) or, failing that, data contract attributes? – dbc Nov 18 '19 at 07:42
  • Because if you can, see [JSON.net: how to deserialize without using the default constructor?](https://stackoverflow.com/q/23017716/3744182). – dbc Nov 18 '19 at 07:50

0 Answers0