将JSON转换为Datatable c#

时间:2018-06-11 13:00:05

标签: c# json asp.net-web-api json.net

我正在尝试将json字符串转换为WEBAPI中的Datatable

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.

3 个答案:

答案 0 :(得分:1)

你无法使用JObject解析数组,你可以阅读更多关于here

的信息

但您可以将其解析为Jarray

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

答案 1 :(得分:0)

回答此OP问题可能为时已晚。但是,如果其他人遇到类似情况,此解决方案可能会有所帮助

使用Cinchoo ETL-一个开源库,您可以轻松地将此json转换为DataTable

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

答案 2 :(得分:-1)

如果它是一个有效的JSON,您可以尝试使用Newtonsoft.Json,那么您可以像这样解析JSON:

var jsonAsObject = JsonConvert.DeserializeObject(json);

如果你有一个JSON模型,你可以像这样转换它:

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