使用 Json.Net 反序列化在某些字段上失败

Deserialize with Json.Net fails on some fields

我尝试使用 Json.Net 将 Json 反序列化为 c# 对象。

c#class:

public class Evaluation
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "avg")]
    public string Average { get; set; }

    [DataMember(Name = "median")]
    public string Median { get; set; }

    [DataMember(Name = "teacherID")]
    public int TeacherId { get; set; }

    [DataMember(Name = "evalType")]
    public int EvaluationType { get; set; }
}

单元测试:

[Test]
[TestCase()]
public void TestParsing()
{
    string json = "{" +
                "\"id\": 439476," +
                "\"avg\": \"69\"," +
                "\"median\": \"75\"," +
                "\"teacherID\": 1," +
                "\"evalType\": 1" +
                "}";

    Evaluation evaluation = JsonConvert.DeserializeObject<Evaluation>(json);

    Assert.IsTrue(evaluation.Average.Equals("69"));
    Assert.IsTrue(evaluation.EvaluationType == 1);
}

这失败了,因为 evaluation.Average 为 null 而 evaluation.EvaluationType 为 0。其他字段被正确解析。

为什么会失败?

在 class 声明中设置 DataContract 属性应该可以解决问题:

[DataContract]
public class Evaluation
{
    [DataMember(Name = "id")]
    public int Id { get; set; }

    [DataMember(Name = "avg")]
    public string Average { get; set; }

    [DataMember(Name = "median")]
    public string Median { get; set; }

    [DataMember(Name = "teacherID")]
    public int TeacherId { get; set; }

    [DataMember(Name = "evalType")]
    public int EvaluationType { get; set; }
}