将两个JSON类与子项合并

时间:2016-12-01 06:34:24

标签: c# angularjs json

我有一个JSON类如下:

malloc

我如何只使用数据表创建一个JSON类,如下所示? 我想在AngularJs.thnx

中的treegrid中使用这个孩子
    [
{
    "url": "", 
    "expanded": false, 
    "label": "Reports", 
    "last_modified": "2014-09-28T11:19:49.000Z", 
    "type": 2, 
    "children": [
        {
            "url": "", 
            "expanded": false, 
            "label": "2014", 
            "last_modified": "2014-09-28T11:19:49.000Z",
          "type": 2
            }}]

1 个答案:

答案 0 :(得分:1)

  

我如何只使用数据表创建一个JSON类,如下所示?

首先,你需要{jen}对象Deserialize。之后,您需要使用反射将此对象映射到DataTable

如果你不理解答案,我强烈建议你谷歌搜索这三颗子弹:

  • 如何将json反序列化为Object
  • 什么是反射,如何使用反射
  • 如何从头开始创建DataTable。

完整示例:dotNetFiddle

    public static void Main(string[] args)
    {
        string json = @" {
        ""children"": [
                {
            ""url"": ""foo.pdf"", 
                    ""expanded"": false, 
                    ""label"": ""E14288-Passive-40085-2014_09_26.pdf"", 
                    ""last_modified"": ""2014-09-28T11:19:49.000Z"", 
                    ""type"": 1, 
                    ""size"": 60929
                }
            ]
         }";

        var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
        DataTable tbl = DataTableFromObject(result.children);
    }

    public static DataTable DataTableFromObject<T>(IList<T> list)
    {
        DataTable tbl = new DataTable();
        tbl.TableName = typeof(T).Name;

        var propertyInfos = typeof(T).GetProperties();
        List<string> columnNames = new List<string>();

        foreach (PropertyInfo propertyInfo in propertyInfos)
        {
            tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
            columnNames.Add(propertyInfo.Name);
        }

        foreach(var item in list)
        {
            DataRow row = tbl.NewRow();
            foreach (var name in columnNames)
            {
                row[name] = item.GetType().GetProperty(name).GetValue(item, null);
            }

            tbl.Rows.Add(row);
        }

        return tbl;
    }

    public class Child
    {
        public string url { get; set; }
        public bool expanded { get; set; }
        public string label { get; set; }
        public DateTime last_modified { get; set; }
        public int type { get; set; }
        public int size { get; set; }
    }

    public class ChildrenRootObject
    {
        public List<Child> children { get; set; }
    }