控制台案例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Xml.Linq;
using System.Net;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string apiUrl = "https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem=06902952880294"; // 替换为实际的 API URL
string jsonResponse = CallApi(apiUrl);
if (!string.IsNullOrEmpty(jsonResponse))
{
DataTable dataTable = CreateDataTable();
JObject jsonData = JObject.Parse(jsonResponse);
JArray items = jsonData["Data"]["Items"] as JArray;
foreach (JObject item in items)
{
DataRow row = dataTable.NewRow();
row["keyword"] = item["keyword"].ToString();
row["branch_code"] = item["branch_code"].ToString();
row["brandid"] = item["brandid"].ToString();
row["brandcn"] = item["brandcn"].ToString();
row["code"] = item["code"].ToString();
row["valid_date"] = item["valid_date"].ToString();
row["logout_date"] = item["logout_date"]?.ToString(); // Handle null value
dataTable.Rows.Add(row);
}
// Now you have the data in the dataTable
// You can use or process the dataTable as needed
Console.ReadLine();
}
}
//查看链接是否正常
static string CallApi(string apiUrl)
{
using (WebClient client = new WebClient())
{
try
{
return client.DownloadString(apiUrl);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return null;
}
}
}
static DataTable CreateDataTable()
{
DataTable dataTable = new DataTable();
dataTable.Columns.Add("keyword");
dataTable.Columns.Add("branch_code");
dataTable.Columns.Add("brandid");
dataTable.Columns.Add("brandcn");
dataTable.Columns.Add("code");
dataTable.Columns.Add("valid_date");
dataTable.Columns.Add("logout_date");
return dataTable;
}
}
}
标签:C#,接口,item,Add,API,ToString,using,dataTable,row From: https://www.cnblogs.com/Yytan-BK/p/17629608.html