用C#读取Json文件

时间:2015-09-26 00:15:48

标签: c# json wpf

如何阅读我的json对象。我有一个带有以下json的json文件

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

我有一个名为DBEnvironment的课程如下

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");
            }
        }
    }

我使用以下代码阅读文件

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

但是dblist是空的。怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

将你的json改为:

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

将您的C#更改为:

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

您还需要一个 Blank Constructor

#region Contructor

public DBEnvironment() 
{
    // Leave blank
}

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

#endregion

<强>解释

您正在寻找DBEnvironment的集合,因此您的json只需要在括号[...]中,并且大括号DBEnvironment中的{...}定义为[ {...}, // First DBEnvironment {...}, // Second {...} // Third ] 。像这样:

{{1}}

您的代码需要反序列化集合,因此选择一个数组就可以了。