反序列化后,json数据给出空引用异常

时间:2015-07-09 17:06:15

标签: c# json deserialization nullreferenceexception

我想在asp.net c#代码中反序列化json数据。我在反序列化语句中收到nullreference异常:

   public static string saveAllTreatments(string jsonval)
        {
            var output =JsonConvert.DeserializeObject<Treatments>(jsonval);
            Treatments tr = (Treatments)output;
            foreach (var item in tr.data)
            {
                Console.WriteLine("date: {0}, number: {1}, name: {2}, note: {3}",item.date, item.number, item.name,item.note);
            }
}

这是我的班级:

public class Treatment
    {
        public DateTime date{ get; set; }
        public int number{ get; set; }
        public string name{ get; set; }
        public string note { get; set; }
    }
    public class Treatments {
        public List<Treatment> data { get; set; }

    }

这是我的json:

{"treatment":[{"date":"09.07.2015","number":"22","name":"Jackson","note":"bla"}]}

我看到jsonval有json数据(它不是null有字符串json数据),我在反序列化输出时收到空引用异常。为什么会这样?

感谢。

2 个答案:

答案 0 :(得分:1)

要将您的c#类与JSON匹配,您需要将data字段的名称更改为treatment

public class Treatments
{
    public List<Treatment> treatment { get; set; }
}

或者,您可以使用JsonProperty属性指定名称:

public class Treatments
{
    [JsonProperty("treatment")]
    public List<Treatment> data { get; set; }
}

示例fiddle

答案 1 :(得分:0)

你可能想要更像这样的东西:

{
"treatment":{
            data:{
           [{"date":"09.07.2015","number":"22","name":"Jackson","note":"bla"}]
                 }
            }
}