简体   繁体   中英

Deserializing a JSON file with c#

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?

要反序列化c#中的代码:让我们假设您在var getContent中有数据,那么您可以使用:

dynamic getDesearilize = JsonConvert.DeserializeObject(getContent);

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.

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