将嵌套的JSON数据解析为DataTable

时间:2015-02-11 09:13:05

标签: c# json datatable

我需要解析下面嵌套在数据表中的一些JSON数据。 3个组中每个组的“属性”字段包含标题,值和优先级的内部数据。

[{
"Title": "OVERVIEW",
"Priority": 1,
"attributes": [{
    "Title": "Type",
    "Value": "MacBook Pro",
    "Priority": 1
    },
    {
       "Title": "Operating system",
       "Value": "OS X Mountain Lion",
       "Priority": 2
    },
    {
       "Title": "Processor",
       "Value": "Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)",
       "Priority": 3
   },
   {
       "Title": "Storage",
       "Value": "500 GB HDDM 5400 rpm",
       "Priority": 4
   }]
},
{
"Title": "SPECIFICATION",
"Priority": 2,
"attributes": [{
    "Title": "RAM",
    "Value": "4 GB DDR3",
    "Priority": 1
    }]
},
{
"Title": "SCREEN",
"Priority": 3,
"attributes": [{
    "Title": "Screen size",
    "Value": "13\"",
    "Priority": 1
    }]
}]

我意识到我需要首先反序列化JSON数据,

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
    TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();

    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];

    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}

但不确定从那里开始,因为上面只考虑了nrmal JSON数据。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

使用此类反序列化数据

         public class TitleDesc
    {
        public string Title { get; set; }
        public int Priority { get; set; }
        public Attribute[] attributes { get; set; }
    }

    public class Attribute
    {
        public string Title { get; set; }
        public string Value { get; set; }
        public int Priority { get; set; }
    }

然后使用此代码序列化

string jsonString = "[{'Title': 'OVERVIEW','Priority': 1,'attributes': [{    'Title': 'Type',    'Value': 'MacBook Pro',    'Priority': 1    },    {       'Title': 'Operating system',       'Value': 'OS X Mountain Lion',       'Priority': 2    },    {       'Title': 'Processor',       'Value': 'Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)',       'Priority': 3   },   {       'Title': 'Storage',       'Value': '500 GB HDDM 5400 rpm',       'Priority': 4   }]},{'Title': 'SPECIFICATION','Priority': 2,'attributes': [{    'Title': 'RAM',    'Value': '4 GB DDR3',    'Priority': 1    }]},{'Title': 'SCREEN','Priority': 3,'attributes': [{    'Title': 'Screen size',    'Value': '13',    'Priority': 1    }]}]";
        var data = JsonConvert.DeserializeObject<TitleDesc[]>(jsonString);

希望这有帮助。