Yytan-BK

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

C# 获取网络API接口中的数据

控制台案例:

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;
        }


        
    }


}

整合版本

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
{

    public class Program
    {
        public static async System.Threading.Tasks.Task Main(string[] args)
        {
            // Step 1: Call the API and get the JSON data
            string apiUrl = "https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem=06902952880294"; // Replace with the actual API URL
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync(apiUrl);

            if (response.IsSuccessStatusCode)
            {
                string jsonResponse = await response.Content.ReadAsStringAsync();

                // Step 2: Deserialize the JSON data
                JObject dataObject = JsonConvert.DeserializeObject<JObject>(jsonResponse);

                // Step 3: Filter and create a new JSON object with selected fields
                JArray itemsArray = dataObject["Data"]["Items"] as JArray;
                JArray filteredItemsArray = new JArray();

                foreach (JObject item in itemsArray)
                {
                    JObject filteredItem = new JObject();
                    filteredItem["keyword"] = item["keyword"];
                    filteredItem["branch_code"] = item["branch_code"];
                    filteredItem["brandid"] = item["brandid"];
                    filteredItem["brandcn"] = item["brandcn"];
                    filteredItem["code"] = item["code"];
                    filteredItem["valid_date"] = item["valid_date"];
                    filteredItem["logout_date"] = item["logout_date"];

                    filteredItemsArray.Add(filteredItem);
                }

                JObject resultObject = new JObject();
                resultObject["FilteredItems"] = filteredItemsArray;

                // Step 4: Serialize the filtered JSON data back to a string
                string filteredJson = JsonConvert.SerializeObject(resultObject, Formatting.Indented);

                // Step 5: Print or return the filtered JSON
                Console.WriteLine(filteredJson);
                
            }
            else
            {
                Console.WriteLine("Failed to fetch data from the API.");
            }
        }
        
    }
}

兼容版本

using Newtonsoft.Json.Linq;
using System;

namespace Test_NetworkInterface_4._0
{
    internal 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"; // Replace with the actual API URL
            HttpClient httpClient = new HttpClient();

            httpClient.GetAsync(apiUrl).ContinueWith(responseTask =>
            {
                HttpResponseMessage response = responseTask.Result;

                if (response.IsSuccessStatusCode)
                {
                    response.Content.ReadAsStringAsync().ContinueWith(readTask =>
                    {
                        string jsonResponse = readTask.Result;

                        // Deserialize JSON
                        JObject dataObject = JObject.Parse(jsonResponse);

                        // Filter and create a new JSON object with selected fields
                        JArray itemsArray = (JArray)dataObject["Data"]["Items"];
                        JArray filteredItemsArray = new JArray();

                        foreach (JObject item in itemsArray)
                        {
                            JObject filteredItem = new JObject();
                            filteredItem["keyword"] = item["keyword"];
                            filteredItem["branch_code"] = item["branch_code"];
                            filteredItem["brandid"] = item["brandid"];
                            filteredItem["brandcn"] = item["brandcn"];
                            filteredItem["code"] = item["code"];
                            filteredItem["valid_date"] = item["valid_date"];
                            filteredItem["logout_date"] = item["logout_date"];

                            filteredItemsArray.Add(filteredItem);
                        }

                        JObject resultObject = new JObject();
                        resultObject["FilteredItems"] = filteredItemsArray;

                        // Serialize the filtered JSON data back to a string
                        string filteredJson = resultObject.ToString();

                        // Print or use the filtered JSON
                        Console.WriteLine(filteredJson);
                    });
                }
                else
                {
                    Console.WriteLine("Failed to fetch data from the API.");
                }
            });

            // Keep the program running until user input
            Console.ReadLine();
        }
    }
}

 

posted on   孤幽影暗  阅读(104)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示