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 }
  • 相关阅读:
    CSS选择器
    python——前端常用的标签
    用socket发送信息在浏览器上显示出来
    Python并发编程-事件驱动模型
    python中的协程
    controller中两个方法之间共享一个变量LinkedHashMap
    分布式缓存和本地缓存
    Java基础方法
    log4j2配置日志大小,个数等
    开发一个根据xml创建代理类的小框架
  • 原文地址:https://www.cnblogs.com/tpfOfBlog/p/6768863.html
Copyright © 2011-2022 走看看