简体   繁体   English

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

[英]json data gives null reference exception after deserialization

I want to deserialize json data in asp.net c# code. 我想在asp.net c#代码中反序列化json数据。 I am receiving nullreference exception in the deserializing statement: 我在反序列化语句中收到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);
            }
}

here is my class: 这是我的课:

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; }

    }

and this is my json: 这是我的json:

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

I see jsonval has json data (its not null has string json data), I receive null reference exception when deserializing to output. 我看到jsonval具有json数据(其非null具有字符串json数据),在反序列化输出时收到null引用异常。 Why is this happening? 为什么会这样呢?

Thanks. 谢谢。

To match your c# class to the JSON, you need to change the name of the data field to treatment : 要将c#类与JSON匹配,您需要将data字段的名称更改为treatment

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

Alternatively, you could specify the name with a JsonProperty attribute: 或者,您可以使用JsonProperty属性指定名称:

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

Example fiddle . 小提琴的例子。

you probably want something more like this: 您可能想要这样的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM