I am deserializing the following class:
public abstract class Tail_Metrics
{
[DataMember(Order = 1, IsRequired = true)]
public double probability { get; set; }
[DataMember(Order = 2, IsRequired = true)]
public double min { get; set; }
[DataMember(Order = 3)]
public double max { get; set; }
[DataMember(Order = 4, IsRequired = true)]
public double mean { get; set; }
[DataMember(Order = 5)]
public double variance { get; set; }
[DataMember(Order = 6)]
public double skewness { get; set; }
[DataMember(Order = 7)]
public double kurtosis { get; set; }
}
public class Layer_Tail_Metrics : Tail_Metrics { }
As you can see, probability, min and average are required, the rest are optional.
I am deserializing the following JSON response from my server:
{
"probability": 0.01,
"mean": 0,
"variance": 0,
"min": 0,
"max": 0
}
And I get Newtonsoft.Json.JsonSerializationExceptionwith a messageRequired property 'probability' not found in JSON. Path '', line 1, position 95.
How can it be? The property is present in JSON and has the correct type!
The strangest thing is that if I remove a property IsRequiredfrom attributes DataMember, I stop receiving this exception, and the object is deserialized perfectly. If any of them has a property IsRequiredset to true, this property throws the same exception.
Deserialization Code:
T retVal = converter.Deserialize<T>(response);
where typeof(T)isLayer_Tail_Metrics
converteris a class that implements RestSharp.Deserializers.IDeserializeras follows:
using Newtonsoft.Json;
public class RestSharp...Converter : RestSharp.Deserializers.IDeserializer
{
private JsonSerializerSettings deserializerSettings;
public RestSharpDataContractNewtonsoftJsonConverter()
{
Culture = CultureInfo.InvariantCulture;
ContentType = "application/json";
deserializerSettings = new JsonSerializerSettings()
{
Converters = new JsonConverter[]{
new Newtonsoft.Json.Converters.IsoDateTimeConverter()
}
};
}
public T Deserialize<T>(IRestResponse response)
{
return Deserialize<T>(response.Content);
}
public T Deserialize<T>(String json)
{
return JsonConvert.DeserializeObject<T>(json, deserializerSettings);
}
}
, :
[DataContract()]
public abstract class Tail_Metrics
{
[DataMember(IsRequired = true)]
public double probability { get; set; }
public Tail_Metrics(double probability)
{
this.probability = probability;
}
}
public class Layer_Tail_Metrics : Tail_Metrics
{
public Layer_Tail_Metrics(double probability) : base(probability) { }
}
class TestClass
{
static void Main(string[] args)
{
string json = @"
{
""probability"": 0.01
}";
Layer_Tail_Metrics tm = Newtonsoft.Json.JsonConvert.DeserializeObject<Layer_Tail_Metrics>(json);
}
}