简体   繁体   中英

json data gives null reference exception after deserialization

I want to deserialize json data in asp.net c# code. I am receiving nullreference exception in the deserializing statement:

   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:

{"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. 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 :

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

Alternatively, you could specify the name with a JsonProperty attribute:

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"}]
                 }
            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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