JSON String to DataTable

Merhaba Arkadaşlar,

Sizinle JSON String’i DataTable’a çeviren bir metod paylaşmak istiyorum.

 Aslında biliyorsunuz bu işlemi Json.NET framework’ü kullanarak kolayca yapabiliyoruz. Ama bazen çeşitli nedenlerle bu framework’ü kullanamayabiliriz. İşte size hiç bir üçüncü parti yazılım kullanmamıza gerek kalmadan JSON String’i DataTable’a çeviren metod:

// how to convert json to datatable in asp.net c#
    protected DataTable ConvertJsonToDatatable(string jsonString)
    {
        DataTable dt = new DataTable();
        //strip out bad characters
        string[] jsonParts = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
 
        //hold column names
        List<string> dtColumns = new List<string>();
 
        //get columns
        foreach (string jp in jsonParts)
        {
            //only loop thru once to get column names
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1);
                    string v = rowData.Substring(idx + 1);
                    if (!dtColumns.Contains(n))
                    {
                        dtColumns.Add(n.Replace("\"", ""));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error Parsing Column Name : {0}", rowData));
                }
 
            }
            break; // TODO: might not be correct. Was : Exit For
        }
 
        //build dt
        foreach (string c in dtColumns)
        {
            dt.Columns.Add(c);
        }
        //get table data
        foreach (string jp in jsonParts)
        {
            string[] propData = Regex.Split(jp.Replace("{", "").Replace("}", ""), ",");
            DataRow nr = dt.NewRow();
            foreach (string rowData in propData)
            {
                try
                {
                    int idx = rowData.IndexOf(":");
                    string n = rowData.Substring(0, idx - 1).Replace("\"", "");
                    string v = rowData.Substring(idx + 1).Replace("\"", "");
                    nr[n] = v;
                }
                catch (Exception ex)
                {
                    continue;
                }
 
            }
            dt.Rows.Add(nr);
        }
        return dt;
    }

 

Kaynak: http://dotnettec.com/convert-json-to-datatable-c-example/

 

 

Bunlar da hoşunuza gidebilir...

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir