Jseb
Jseb

Reputation: 1934

Read a Json File with C#

How can I read my json objects. I have a json file with the following json

{
    "DBEnvironment": [
        {
            "dbID": 1,
            "dbName": "Develop"
        },
        {
            "dbID": 2,
            "dbName": "Test"
        },
        {
            "dbID": 3,
            "dbName": "Production"
        }
    ]
}

I have a class called DBEnvironment as 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
        {
            get { return _dbID; }
            set
            {
                _dbID = value;
                OnPropertyChanged("ID changed");
            }
        }
        public string dbName
        {
            get { return _dbName; }

            set
            {
                _dbName = value;
                OnPropertyChanged("Database Name");
            }
        }
    }

I read the file with the following codes

 string json = File.ReadAllText(path);
 DBEnvironment dblist = JsonConvert.DeserializeObject<DBEnvironment>(json);
 MessageBox.Show(dblist.dbName);

But dblist is empty. How to solve this?

Upvotes: 0

Views: 291

Answers (1)

Laith
Laith

Reputation: 6091

Change your json to this:

[
    {
        "dbId": 1,
        "dbName": "Develop"
    },
    {
        "dbId": 2,
        "dbName": "Test"
    },
    {
        "dbId": 3,
        "dbName": "Production"
    }
]

And change your C# to this:

string json = File.ReadAllText(path);
DBEnvironment[] dblist = JsonConvert.DeserializeObject<DBEnvironment[]>(json);
MessageBox.Show(dblist[0].dbName);

You'll also need a Blank Constructor

#region Contructor

public DBEnvironment() 
{
    // Leave blank
}

public DBEnvironment(int id, string name)
{
    _dbID = id;
    _dbName = name;
}

#endregion

Explanation

You're looking for a collection of DBEnvironment, so your json just needs to be in brackets [...] with each definition of DBEnvironment in curly braces {...}. Like this:

[
   {...}, // First DBEnvironment
   {...}, // Second
   {...}  // Third
]

Your code needs to deserialize a collection, so choosing an array would do.

Upvotes: 2

Related Questions