簡體   English   中英

將 JSON 轉換為數據表 c#

[英]Convert JSON to Datatable c#

我正在嘗試將 json 字符串轉換為 WEBAPI 中的數據表

The json string looks like
[
[
    "Test123",
    "TestHub",
    "TestVersion",
    "TestMKT",
    "TestCAP",
    "TestRegion",
    "TestAssembly",
    "TestProduct",
    "Testgroup",
    "Testsample",
    "1806",
    "1807",
    "1808",
    "1809",
    "1810",
    "1811",
    "1812",
    "1901",
    "1902",
    "1903",
    "1904",
    "1905",
    "1906",
    "1907",
    "1908",
    "1909",
    "1910",
    "1911",
    "1912"
],
[
    "Sample12",
    "Sample879",
    "201806.1.0",
    "Sample098",
    "TSA CBU",
    "B8",
    "B8",
    "63",
    "63EM",
    "EM 42 T",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0"
],
[
    "Sample121233",
    "Sample233879",
    "2012323806.1.0",
    "Sampl233e098",
    "TSA CBU",
    "B8",
    "B8",
    "B3",
    "B3ULUE",
    "UL 42 R",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0",
    "0"
]
]

我在其中發布 json 的 WEBAPI 方法我想將 json 轉換為具有一些默認列名的數據表 ..................................... ………………………………………………………………………………………………………………………………………………………… ...

public async Task<HttpResponseMessage> Uploadjson(HttpRequestMessage request)
    {
        try
        {
            var jsonString = await request.Content.ReadAsStringAsync();
            var jArrayObj = JsonConvert.DeserializeObject<JArray>(jsonString);
            JArray jsonArray = JArray.Parse(jsonString) as JArray;

           DataTable dt = JsonToDataTable(jsonArray[0].ToString());

        }
        catch (Exception exception)
        {
            Log.Info("EndPoint Out Time :" + DateTime.Now.ToString());
        }

        return new HttpResponseMessage(HttpStatusCode.OK);
    }

這是我的 JsonToDataTable 方法

    public static DataTable JsonToDataTable(string json)
    {
        var jsonLinq = JObject.Parse(json);

        // Find the first array using Linq
        var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
        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);
        }

        return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());

        //bool columnsCreated = false;
        //DataTable dt = new DataTable(tableName);

        //Newtonsoft.Json.Linq.JObject root = Newtonsoft.Json.Linq.JObject.Parse(json);
        //Newtonsoft.Json.Linq.JArray items = root(tableName);

        //Newtonsoft.Json.Linq.JObject item = default(Newtonsoft.Json.Linq.JObject);
        //Newtonsoft.Json.Linq.JToken jtoken = default(Newtonsoft.Json.Linq.JToken);

        //for (int i = 0; i <= items.Count - 1; i++)
        //{
        //    // Create the columns once
        //    if (columnsCreated == false)
        //    {
        //        item = (Newtonsoft.Json.Linq.JObject) items(i);
        //        jtoken = item.First;

        //        while (jtoken != null)
        //        {
        //            dt.Columns.Add(new DataColumn(((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()));
        //            jtoken = jtoken.Next;
        //        }

        //        columnsCreated = true;
        //    }

        //    // Add each of the columns into a new row then put that new row into the DataTable
        //    item = (Newtonsoft.Json.Linq.JObject)items(i);
        //    jtoken = item.First;

        //    // Create the new row, put the values into the columns then add the row to the DataTable
        //    DataRow dr = dt.NewRow;

        //    while (jtoken != null)
        //    {
        //        dr(((Newtonsoft.Json.Linq.JProperty)jtoken).Name.ToString()) = ((Newtonsoft.Json.Linq.JProperty)jtoken).Value.ToString();
        //        jtoken = jtoken.Next;
        //    }

        //    dt.Rows.Add(dr);
        //}

        //return dt;

    }

在 var jsonLinq = JObject.Parse(json); 我收到錯誤

  Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.

你不能用 JObject 解析數組,你可以在這里閱讀更多關於它的信息

但您可以將其解析為Jarray

JArray jsonArray = JArray.Parse(json);
foreach (JArray arrayRow in jsonArray)
        {
            foreach (JToken arrayItem in arrayRow))
            {
                //do stuff here
            }
        }

回答這個 OP 問題可能為時已晚。 但是,如果其他人遇到類似情況,此解決方案可能會有所幫助

使用Cinchoo ETL - 一個開源庫,您可以輕松地將此 json 轉換為 DataTable

using (var r = ChoJSONReader.LoadText(json))
{
    DataTable dt = r.Select(rec => ((object[])rec.Value).ToDictionary()).AsDataTable();
}

如果它是一個有效的 JSON,你可以嘗試使用 Newtonsoft.Json 然后你可以像這樣解析 JSON:

var jsonAsObject = JsonConvert.DeserializeObject(json);

如果你有一個 JSON 模型,你可以像這樣轉換它:

ModelName model = (ModelName)JsonConvert.DeserializeObject(json, typeof(ModelName));

暫無
暫無

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

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