C#遍歷json內容,並新增到DataTable裡面作為列

2020-10-11 13:00:18

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);
           }
	 }
// <summary>
        /// 替換「{」,「}」
        /// </summary>
        /// <param name="strRep"></param>
        /// <returns></returns>
        private string replaceStr(string strRep)
        {
            if (!string.IsNullOrEmpty(strRep)&& strRep.Contains("{") && strRep.Contains("}"))
            {
                string str = strRep.Replace("{", "").Replace("}", "");
                return str;
            }
            else
                return "";
        }