我尝试使用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.其他字段已正确解析。
为什么会失败?
答案 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; }
}