如何使用asp.net将嵌套的json转换为datatable

时间:2018-04-20 12:47:00

标签: asp.net json datatable

您好我正在使用C#调用webapi。它返回json数据。它是嵌套的JSON。如何将此JSON字符串转换为Datatable。我已经阅读了许多建议使用类的帖子,但我的json字符串有多个分支。如何在不使用类的情况下将此Json字符串转换为Datatable:

(2/2) ContextErrorException
Warning: file_put_contents(/srv/http/ocim.formations/var/cache/dev/appDevDebugProjectContainerDeprecations.log): failed to open stream: Permission denied
in Kernel.php (line 648)

(1/2) FatalThrowableError
Call to undefined method Doctrine\Bundle\DoctrineCacheBundle\Command\ContainsCommand::getDefaultName()
in AddConsoleCommandPass.php (line 61)

它是json的一小部分,这部分重复了十次或更多次,任何人请帮忙

1 个答案:

答案 0 :(得分:0)

试试这个:

首先创建函数:

public DataTable JsonStringToDataTable(string jsonString)
   {
      DataTable dt = new DataTable();
      string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
      List<string> ColumnsName = new List<string>();
      foreach (string jSA in jsonStringArray)
      {
         string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
         foreach (string ColumnsNameData in jsonStringData)
         {
            try
            {
               int idx = ColumnsNameData.IndexOf(":");
               string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
               if (!ColumnsName.Contains(ColumnsNameString))
               {
                  ColumnsName.Add(ColumnsNameString);
               }
            }
            catch (Exception ex)
            {
               throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
            }
         }
         break;
      }
      foreach (string AddColumnName in ColumnsName)
      {
         dt.Columns.Add(AddColumnName);
      }
      foreach (string jSA in jsonStringArray)
      {
         string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
         DataRow nr = dt.NewRow();
         foreach (string rowData in RowData)
         {
            try
            {
               int idx = rowData.IndexOf(":");
               string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
               string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
               nr[RowColumns] = RowDataString;
            }
            catch (Exception ex)
            {
               continue;
            }
         }
         dt.Rows.Add(nr);
      }
      return dt;
   }

调用此函数:

Datatabel dt = JsonStringToDataTable(JsonString) // put your json string here