簡體   English   中英

動態嵌套 JSON 數據到數據表 C#

[英]Nested JSON data to datatable dynamically C#

{
    "STATUS": "OK",
    "projects": [
        {
            "startDate": "",
            "last-changed-on": "2019-01-03T11:46:14Z",
            "logo": "",
            "created-on": "2018-12-12T10:04:47Z",
            "privacyEnabled": false,
            "status": "active",
            "boardData": {},
            "replyByEmailEnabled": true,
            "harvest-timers-enabled": false,
            "description": "",
            "category": {
                "color": "",
                "id": "",
                "name": ""
            },
            "id": "322852",
            "overview-start-page": "default",
            "start-page": "projectoverview",
            "integrations": {
                "xero": {
                    "basecurrency": "",
                    "countrycode": "",
                    "enabled": false,
                    "connected": "NO",
                    "organisation": ""
                },
                "sharepoint": {
                    "account": "",
                    "foldername": "root",
                    "enabled": false,
                    "folder": "root"
                },
                "microsoftConnectors": {
                    "enabled": false
                },
                "onedrivebusiness": {
                    "account": "",
                    "foldername": "root",
                    "enabled": false,
                    "folder": "root"
                }
            },
            "defaults": {
                "privacy": ""
            },
            "notifyeveryone": false,
            "filesAutoNewVersion": false,
            "defaultPrivacy": "open",
            "tasks-start-page": "default",
            "starred": false,
            "announcementHTML": "",
            "isProjectAdmin": true,
            "name": "Project 2",
            "company": {
                "is-owner": "1",
                "id": "78494",
                "name": "MCG Company"
            },
            "endDate": "",
            "announcement": "",
            "show-announcement": false,
            "subStatus": "current",
            "tags": []
        },
        {
            "startDate": "",
            "last-changed-on": "2018-12-11T17:52:57Z",
            "logo": "",
            "created-on": "2018-11-26T11:11:00Z",
            "privacyEnabled": false,
            "status": "active",
            "boardData": {},
            "replyByEmailEnabled": true,
            "harvest-timers-enabled": false,
            "description": "",
            "category": {
                "color": "",
                "id": "",
                "name": ""
            },
            "id": "321041",
            "overview-start-page": "default",
            "portfolioBoards": [
                {
                    "card": {
                        "id": "4771"
                    },
                    "board": {
                        "id": "544",
                        "name": "Project Implementations",
                        "color": "#F39C12"
                    },
                    "column": {
                        "id": "1573",
                        "name": "Go Live",
                        "color": "#F1C40F"
                    }
                }
            ],
            "start-page": "projectoverview",
            "integrations": {
                "xero": {
                    "basecurrency": "",
                    "countrycode": "",
                    "enabled": false,
                    "connected": "NO",
                    "organisation": ""
                },
                "sharepoint": {
                    "account": "",
                    "foldername": "root",
                    "enabled": false,
                    "folder": "root"
                },
                "microsoftConnectors": {
                    "enabled": false
                },
                "onedrivebusiness": {
                    "account": "",
                    "foldername": "root",
                    "enabled": false,
                    "folder": "root"
                }
            },
            "defaults": {
                "privacy": ""
            },
            "notifyeveryone": false,
            "filesAutoNewVersion": false,
            "defaultPrivacy": "open",
            "tasks-start-page": "default",
            "starred": false,
            "announcementHTML": "",
            "isProjectAdmin": true,
            "name": "Project One",
            "company": {
                "is-owner": "1",
                "id": "78494",
                "name": "MCG Company"
            },
            "endDate": "",
            "announcement": "",
            "show-announcement": false,
            "subStatus": "current",
            "tags": []
        }
    ]
}

這是我從應用程序獲得的 JSON 響應,還有很多其他 API 獲得返回相同類型的響應(嵌套),所以當用戶從 ZDB974238714CA8DE634ACE 調用從一個配置文件,所以我不能用gets和sets制作預制類。 我的目標是將此數據轉換為要插入數據庫的數據表當我看到嵌套列時,我的目標是使用“_”附加父列名稱 例如:category_id = “”或 integrations_xero_basecurrency = “ “, ETC..

這是我用來將數據制成表格的代碼,但在代碼中,如果它是 JValue(鍵和值),它只會占用列,而且我無法在我的一生中創建一個合適的循環來做訣竅。

    public DataTable Tabulate(string jsonContent)
    {
        var jsonLinq = JObject.Parse(jsonContent);

        // Find the first array using Linq
        var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
        //Console.WriteLine("extarcted data:" + srcArray);
        var trgArray = new JArray();
        foreach (JObject row in srcArray.Children<JObject>())
        {
            var cleanRow = new JObject();
            foreach (JProperty column in row.Properties())
            {
                // Only include JValue types
                if (column.Value is JValue)
                {
                    cleanRow.Add(column.Name, column.Value);
                }
            }

            trgArray.Add(cleanRow);
        }

        DataTable dt = JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());            

        return dt;
    }

像這樣的東西怎么樣:

public DataTable Tabulate(string jsonContent)
{
    var jsonLinq = JObject.Parse(jsonContent);

    // Find the first array using Linq
    var arrayProp = jsonLinq.Properties().First(p => p.Value is JArray);
    var srcArray = (JArray)arrayProp.Value;

    // Set up a regex consisting of the array property name and subscript 
    // (e.g. "projects[0]."), which we will strip off
    var regex = new Regex($@"^{arrayProp.Name}\[\d+\]\.");

    // Flatten each object of the original array 
    // into new objects and put them in a new array 
    var trgArray = new JArray(
        srcArray.Children<JObject>()
                .Select(row => new JObject(
                     row.Descendants()
                        .OfType<JProperty>()
                        .Where(p => p.Value is JValue)
                        .Select(p => new JProperty(
                            regex.Replace(p.Value.Path, "").Replace(".", "_"), 
                            p.Value
                        ))
                ))
        );

    // Convert the new array to a DataTable
    DataTable dt = trgArray.ToObject<DataTable>();

    return dt;
}

工作演示: https://dotnetfiddle.net/yrmcSQ

暫無
暫無

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

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