C#遍历json内容,并添加到DataTable里面作为列

C#遍历json内容,并添加到DataTable里面作为列

直接看代码,不啰嗦!
简单易懂,希望对你有帮助,若有帮助,给个赞吧!

先看json格式
{“ProdSN”:"{SerialNumber}",“EqpID”:"{EqpID}",“Parameter”:[{“ParaName”:“overallResult”,“ParaValue”:"{overallResult}"},{“ParaName”:“errCode”,“ParaValue”:"{errCode}"},{“ParaName”:“startTime”,“ParaValue”:"{startTime}"},{“ParaName”:“stopTime”,“ParaValue”:"{stopTime}"},{“ParaName”:“testerID”,“ParaValue”:"{testerID}"}]}

代码实现
需要引用:using Newtonsoft.Json.Linq;

string[] lines = null;
string Path = System.AppDomain.CurrentDomain.BaseDirectory + "\\CONFIGURATION_TABLE";
string strFullJosnPath = Path + "\\" + "Trackout_test.json";
 if (File.Exists(strFullJosnPath))
                    {
     
                        lines = File.ReadAllLines(strFullJosnPath, Encoding.UTF8);
                    }
 string strParaNamesReplace = lines[0];
 DataTable dtNewTemp = new DataTable();
DataColumn dc = null;
JObject jObject = JObject.Parse(strParaNamesReplace);
foreach (JProperty jProperty in jObject.Properties())
       {
     
         if (jProperty.Name.Contains("Parameter"))
           {
     
            JToken retDataJson = JToken.Parse(jProperty.Value.ToString());
              foreach (JToken item in retDataJson)//遍历数组
               {
     
                 String tmuid = item["ParaValue"].ToString();
                 dc = new DataColumn();
                 dc.ColumnName = replaceStr(tmuid);
                dtNewTemp.Columns.Add(dc);                             
               }
            }
          else
           {
     
             dc = new DataColumn();
             dc.ColumnName = replaceStr(jProperty.Value.ToString());
             dtNewTemp.Columns.Add(dc);
           }
	 }
// 
        /// 替換“{”,“}”
        /// 
        /// 
        /// 
        private string replaceStr(string strRep)
        {
     
            if (!string.IsNullOrEmpty(strRep)&& strRep.Contains("{") && strRep.Contains("}"))
            {
     
                string str = strRep.Replace("{", "").Replace("}", "");
                return str;
            }
            else
                return "";
        }

你可能感兴趣的:(c#,json)