使用C#将JSON嵌套数组反序列化为DataTable

时间:2017-10-04 08:58:30

标签: c# json json.net

我需要帮助使用Newtsonsoft.json(JSON.NET)将JSON输出反序列化为C#中的数据表。我在这个和许多其他论坛上看过很多关于磁盘的例子,但我无法弄清楚如何做到这一点。

要反序列化的JSON示例:

[{
"display_name": "Check MWExternal",
"plugin_output": "MWExternal.exe: not running",
"host": {
  "name": "WIN2008.arlaplast.local"
} },{
"display_name": "Swap usage",
"plugin_output": "Paging File usage is  = 39.19 %",
"host": {
  "name": "srvdccz01.arlaplast.local"
}},{
"display_name": "Swap usage",
"plugin_output": "Paging File usage is  = 40 %",
"host": {
  "name": "srvdccz02.arlaplast.local"
}}]

响应结构看起来总是相同但可以有很多块

我想在一张看起来像这样的表中

Table example

到目前为止,这是我的代码:(只给我表中的前两列,而不是host.name)

    public partial class test : System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
{
    PopulateList();
}

    public class Host
    {
        public string name { get; set; }
    }

    public class RootObject
    {
        public string display_name { get; set; }
        public string plugin_output { get; set; }
        public Host host { get; set; }
    }

    public static DataTable ToDataTable<T>(List<T> items)
{
    DataTable dataTable = new DataTable(typeof(T).Name);

    //Get all the properties
    System.Reflection.PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (PropertyInfo prop in Props)
    {
        //Defining type of data column gives proper data table 
        var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);

            //Setting column names as Property names
        dataTable.Columns.Add(prop.Name, type);
    }
    foreach (T item in items)
    {
        var values = new object[Props.Length];
        for (int i = 0; i < Props.Length; i++)
        {
            //inserting property values to datatable rows
            values[i] = Props[i].GetValue(item, null);
        }
        dataTable.Rows.Add(values);
    }
    //put a breakpoint here and check datatable
    return dataTable;
}


public void PopulateList()
{
    string uri = "https://op5.ateavdc.se/api/filter/query?query=[services]%20state!=0&columns=display_name,plugin_output,host.name";
    string _auth = string.Format("{0}:{1}", "USERNAME", "PASSWÒRD");
    string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
    string _cred = string.Format("{0} {1}", "Basic", _enc);

    try
    {
        dynamic webRequest__1 = (HttpWebRequest)WebRequest.Create(uri);
        webRequest__1.Headers.Add("Authorization", _cred);
        webRequest__1.ContentType = "application/json; charset=utf-8";
        webRequest__1.Method = "GET";
        dynamic webResponse = (HttpWebResponse)webRequest__1.GetResponse();

        if (webResponse.StatusCode == HttpStatusCode.OK)
        {
            dynamic reader = new StreamReader(webResponse.GetResponseStream());
            string s = reader.ReadToEnd();
                TextBox1.Text = s.ToString();

                var data = JsonConvert.DeserializeObject<List<RootObject>>(s);
                DataTable dt = ToDataTable(data);
                GridView1.DataSource = dt;
                GridView1.DataBind();

            }
        else
        {
                Response.Write(webResponse.StatusCode);
        }
    }
    catch (Exception ex)
    {
            Response.Write(ex.Message);
        }}}

2 个答案:

答案 0 :(得分:0)

根据提供的示例,考虑到你知道嵌套的Json将如何出现,让我们创建类,

sudo lsof -iTCP -sTCP:LISTEN -n -P

现在让我们使用public class Host { public string name { get; set; } } public class RootObject { public string display_name { get; set; } public string plugin_output { get; set; } [JsonProperty("host")] public Host h { get; set; } public string Host { get { return this.h.name;} set {this.h.name = value;}} }

进行DeserializeObject
NewtonSoft

您将获得如下输出

enter image description here

然后,如果您使用linq进行过滤,

string s = "[{\"display_name\": \"Check MWExternal\",\"plugin_output\": \"MWExternal.exe: not running\",\"host\": { \"name\": \"WIN2008.arlaplast.local\"} },{\"display_name\": \"Swap usage\",\"plugin_output\": \"Paging File usage is = 39.19 %\",\"host\": { \"name\": \"srvdccz01.arlaplast.local\"}},{\"display_name\": \"Swap usage\",\"plugin_output\": \"Paging File usage is = 40 %\",\"host\": { \"name\": \"srvdccz02.arlaplast.local\"}}]"; JsonConvert.DeserializeObject<List<RootObject>>(s);

enter image description here

希望这会有所帮助..!

答案 1 :(得分:0)

最简单的解决方案:

var json = File.ReadAllText("data.json");

var arr = JArray.Parse(json);

var data = arr.Select(x => new
{
    DisplayName = x.Value<string>("display_name"),
    PluginOutput = x.Value<string>("plugin_output"),
    Host = x.Value<JToken>("host").Value<string>("name")
})
.ToList();