zoukankan      html  css  js  c++  java
  • 使用Newtonsoft JsonConvert反序列化Json数据到DataTable

    要用到Newtonsoft.Json.dll

    简单了解JArray和JObject

    string json = @"[
                { id: 1, title: '必订款', no: 'bdk', flag_ka: 'y' },
                { id: 2, title: '必订规格', no: 'bdgg', flag_ka: 'n' }
            ]";
    Newtonsoft.Json.Linq.JArray array = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as JArray;
    for (int i = 0; i < array.Count; i++)
    {
        JObject obj = array[i] as JObject;
        int id = Convert.ToInt32(obj["id"]);
        var title = obj["title"];
    }

    Json转DataTable

     1 string json = @"[
     2             { id: 1, title: '必订款', no: 'bdk', flag_ka: 'y' },
     3             { id: 2, title: '必订规格', no: 'bdgg', flag_ka: 'n' }
     4         ]";
     5 Newtonsoft.Json.Linq.JArray array = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as JArray;
     6 StringBuilder columns = new StringBuilder();
     7 DataTable table = new DataTable();
     8 JObject objColumns = array[0] as JObject;
     9 //构造表头
    10 foreach (JToken jkon in objColumns.AsEnumerable<JToken>())
    11 {
    12     string name = ((JProperty)(jkon)).Name;
    13     columns.Append(name + ",");
    14     table.Columns.Add(name);
    15 }
    16 //向表中添加数据
    17 for (int i = 0; i < array.Count; i++)
    18 {
    19     DataRow row = table.NewRow();
    20     JObject obj = array[i] as JObject;
    21     foreach (JToken jkon in obj.AsEnumerable<JToken>())
    22     {
    23         string name = ((JProperty)(jkon)).Name;
    24         string value = ((JProperty)(jkon)).Value.ToString();
    25         row[name] = value;
    26     }
    27     table.Rows.Add(row);
    28 }
  • 相关阅读:
    3. 无重复字符的最长子串
    24. 两两交换链表中的节点
    2. 两数相加
    23. 合并K个排序链表
    synergy配置 Ubuntu作Server, Win 7作client
    ros与下位机通信常用的c++ boost串口应用
    tar
    发布里程计传感器信息
    ROS TF——learning tf
    在linux终端下打开pdf文件
  • 原文地址:https://www.cnblogs.com/tpfOfBlog/p/6768863.html
Copyright © 2011-2022 走看看