簡體   English   中英

將 Json 字符串轉換為 C# 中的數據表

[英]Convert Json String to Datatable in C#

我有以下 Json 字符串需要轉換為數據表 C#

[ { "Genre": "Fiction", "Author": "J K Rowling", "Books": [ { "Name": "Philospher's Stone", "Published": "1997" }, { "Name": "Chamber of Secrets", "Published": "1998" }, { "Name": "Prisoner of Azkaban", "Published": "1999" }, { "Name": "Goblet of Fire", "Published": "2000" }, { "Name": "Order of Phoenix", "Published": "2003" } ] }, { "Genre": "Non Fiction", "Author": "George Orwell", "Books": [ { "Name": "Animal Farm", "Published": "1952" }, { "Name": "Nineteen Eighty Four", "Published": "1949" } ] } ]

數據表:

類型 作者 圖書 發表
小說 JK羅琳 哲學家的石頭 1997
小說 JK羅琳 密室 1998
小說 JK羅琳 阿茲卡班的囚徒 1999
小說 JK羅琳 火焰杯 2000
小說 JK羅琳 鳳凰社 2003年
非小說類 喬治奧威爾 動物農場 1952年
非小說類 喬治奧威爾 一九八四 1949年

您可以將 json object 反序列化為某些 class。

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

然后像這樣從這個列表中填充數據表。

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            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;
 }

歡迎來到stackoverflow。 對於此類問題,我總是使用https://json2csharp.com/之類的頁面將 json 轉換為 csharp 對象。 你可以復制它,然后給它起有意義的名字。

但是您可以直接使用 JsonConvert 反序列化您的 json - 字符串,您可以使用它。 我喜歡使用 DomainObjects 將其與 EntityFramework 一起保存在數據庫中。

public class DomainObject
{
    public string Name { get; set; } 
    public string Published { get; set; } 
    public string Genre { get; set; } 
    public string Author { get; set; } 
}


[Fact]
public void Test()
{
    Root root = JsonConvert.DeserializeObject<Root>( jsonString );

    DomainObject[] values = root.Books.Select( x => new DomainObject()
            { Author = root.Author, Genre = root.Genre, Name = x.Name, Published = x.Published } )
           .ToArray();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM