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

时间:2015-05-13 12:07:54

标签: c# json json.net deserialization

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

c#c​​lass:

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.其他字段已正确解析。

为什么会失败?

1 个答案:

答案 0 :(得分:4)

在类声明上设置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; }
}