Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserializing a JSON file with c#

Tags:

My problem is i have this JSON file:

and i have to save it in a list but when i try to print the first element of the list I get a System.ArgumentOutOfRangeException, as if my list is empty. this is my code:

JavaScriptSerializer ser = new JavaScriptSerializer();            
        Causali o = new Causali();
        List<CausaliList> lista = new List<CausaliList>();
        WebRequest causali = (HttpWebRequest)WebRequest.Create("http://trackrest.cgestmobile.it/causali");
        WebResponse risposta = (HttpWebResponse)CreateCausaliRequest(causali).GetResponse();
        Stream data = risposta.GetResponseStream();
        StreamReader Leggi = new StreamReader(data);            
        string output = Leggi.ReadToEnd();
        lista = ser.Deserialize<List<CausaliList>>(output);
        lst2.Items.Add(lista[0]);

and these are my two class for the saves:

class Causali
    {
        public int id;
        public string causaliname;
        public string identificationcode;
        public string expired;
    }   

and

class CausaliList
    {
        public Causali causali;       
    }

can you help me solve it?

like image 230
Lorenzo Valenti Avatar asked Jun 06 '17 10:06

Lorenzo Valenti


1 Answers

please try this as your root object:

public class CausaliList
{
    public List<Causali> causali { get; set; }
}

then deserilize your object like this:

lista = ser.Deserialize<CausaliList>(output); 

finally you can access to list like this:

lst2.Items.Add(lista.causali[0]);

Note: i strongly recommend to use json.NET.

like image 99
Mohammad Avatar answered Sep 29 '22 23:09

Mohammad