Read a Json File with C# -


how can read json objects. have json file following json

{     "dbenvironment": [         {             "dbid": 1,             "dbname": "develop"         },         {             "dbid": 2,             "dbname": "test"         },         {             "dbid": 3,             "dbname": "production"         }     ] } 

i have class called dbenvironment follow

class dbenvironment : inotifypropertychanged     {         #region data          private int _dbid;         private string _dbname;          #endregion          #region contructor          public dbenvironment(int id, string name)         {             _dbid = id;             _dbname = name;         }          #endregion         public int dbid         {             { return _dbid; }             set             {                 _dbid = value;                 onpropertychanged("id changed");             }         }         public string dbname         {             { return _dbname; }              set             {                 _dbname = value;                 onpropertychanged("database name");             }         }     } 

i read file following codes

 string json = file.readalltext(path);  dbenvironment dblist = jsonconvert.deserializeobject<dbenvironment>(json);  messagebox.show(dblist.dbname); 

but dblist empty. how solve this?

change json this:

[     {         "dbid": 1,         "dbname": "develop"     },     {         "dbid": 2,         "dbname": "test"     },     {         "dbid": 3,         "dbname": "production"     } ] 

and change c# this:

string json = file.readalltext(path); dbenvironment[] dblist = jsonconvert.deserializeobject<dbenvironment[]>(json); messagebox.show(dblist[0].dbname); 

you'll need blank constructor

#region contructor  public dbenvironment()  {     // leave blank }  public dbenvironment(int id, string name) {     _dbid = id;     _dbname = name; }  #endregion 

explanation

you're looking collection of dbenvironment, json needs in brackets [...] each definition of dbenvironment in curly braces {...}. this:

[    {...}, // first dbenvironment    {...}, // second    {...}  // third ] 

your code needs deserialize collection, choosing array do.


Comments