我正在反序列化到以下类:
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 { }
如您所见,概率、最小值和均值是必需的,其余是可选的。
我正在反序列化来自我的服务器的以下 JSON 响应:
{
"probability": 0.01,
"mean": 0,
"variance": 0,
"min": 0,
"max": 0
}
我收到了一条Newtonsoft.Json.JsonSerializationException
消息Required property 'probability' not found in JSON. Path '', line 1, position 95.
怎么可能?该属性存在于 JSON 中,并且具有正确的类型!
最奇怪的是,如果我IsRequired
从属性中删除该DataMember
属性,我将不再收到此异常,并且对象会完美地反序列化。如果其中任何一个将IsRequired
属性设置为 true,则该属性将引发相同的异常。
反序列化代码为:
T retVal = converter.Deserialize<T>(response);
typeof(T)
在哪里Layer_Tail_Metrics
converter
是一个实现RestSharp.Deserializers.IDeserializer
如下的类:
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);
}
}