C#实现调用接口数据获取数据格式化XML、json转成Table的方法
废话不多说,直接上代码:
json 格式化转DataTable:
result为从接口得到的数据,格式化json的方法主要来自Newtonsoft.Json
JObject joUnit = JObject.Parse(result);
string a = Convert.ToString(joUnit["data"]["UnitComInfoList"]);
JArray jo = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(a);//反序列化为数组
DataTable table = DerializeToDataTable(jo, "UnitComInfoList");
/// <summary>
/// 创建datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jo"></param>
/// <returns></returns>
public DataTable DerializeToDataTable(JArray jo, string TableName)
{
DataTable table = new DataTable();
table.TableName = TableName;
if (jo.Count > 0)
{
StringBuilder columns = new StringBuilder();
JObject objColumns = jo[0] as JObject;
//构造表头
foreach (JToken jkon in objColumns.AsEnumerable<JToken>())
{
string name = ((JProperty)(jkon)).Name;
columns.Append(name + ",");
table.Columns.Add(name);
}
//向表中添加数据
for (int i = 0; i < jo.Count; i++)
{
DataRow row = table.NewRow();
JObject obj = jo[i] as JObject;
foreach (JToken jkon in obj.AsEnumerable<JToken>())
{
string name = ((JProperty)(jkon)).Name;
string value = ((JProperty)(jkon)).Value.ToString();
row[name] = value;
}
table.Rows.Add(row);
}
}
return table;
}
xml格式化转DataTable:
public DataTable GetXMLData(string ResultXml)
{
XmlDocument doc = new XmlDocument();
DataTable newdt = new DataTable();
doc.LoadXml(ResultXml);
XmlNode nodeList = doc.SelectSingleNode("ReturnData").SelectSingleNode("Data");
if (nodeList != null)
{
DataTable dt = getDataTableFromXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + nodeList.OuterXml);
newdt = dt.Clone(); // 克隆dt 的结构,包括所有 dt 架构和约束,并无数据;
DataRow[] arrRows = dt.Select();
foreach (DataRow row in arrRows) // 将查询的结果添加到dt中;
{
newdt.Rows.Add(row.ItemArray);
}
}
return newdt;
}
/// 从XML生成DT
/// </summary>
/// <param name="sourceXml"></param>
/// <returns></returns>
public static DataTable getDataTableFromXml(string sourceXml)
{
if (sourceXml == null) return null;
DataTable mydt = new DataTable();
System.IO.StringReader sr = new System.IO.StringReader(sourceXml);
XmlTextReader myXmlTextReader = new XmlTextReader(sr);
DataSet ds = new DataSet();
ds.ReadXml(myXmlTextReader, XmlReadMode.Auto);
if (ds.Tables.Count > 0)
mydt = ds.Tables[0];
return mydt;
}