C#: Отправить и обработать запрос JSON

В прошлый раз я написал скрипт на PowerShell, который отправлял на сервер запрос, получал ответ в JSON, затем выводил информацию в консоль. Всё работало, но было неудобно из-за того, что это был скрипт, поэтому приходилось его вызывать из консоли, а чтобы вызвать его из внешнего приложения, приходилось заморачиваться с аргументами. В общем и на этот раз заказчик захотел что-то другое. В качестве «другого» могло подойти консольное приложение на C#.

Чувствую, что, такими темпами, мне придётся скоро изучать 1С (чтобы сразу из формы отправлять запрос) :)

 

Здесь я привожу пример опять же «на заметку», потому что тут пришлось уже поднапрячься — это оказалось сложнее скрипта на PowerShell. В основном из-за того, что пришлось искать замену устаревшему WebRequest:

Don’t use WebRequest or its derived classes for new development. Instead, use the System.Net.Http.HttpClient class.

 

Program.cs
using Newtonsoft.Json.Linq;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Text.Json.Serialization;

namespace ParseJSON
{
    public class UPSData
    {
        [JsonPropertyName("status")]
        public string? Status { get; set; }
        [JsonPropertyName("error")]
        public string? Error { get; set; }
        [JsonPropertyName("sn")]
        public string? Serial { get; set; }
        [JsonPropertyName("sn_exception")]
        public string? Sn_exception { get; set; }
        [JsonPropertyName("imei1")]
        public string? Imei1 { get; set; }
        [JsonPropertyName("imei2")]
        public string? Imei2 { get; set; }
        [JsonPropertyName("model")]
        public string? Model { get; set; }
        [JsonPropertyName("full_name")]
        public string? Full_name { get; set; }
        [JsonPropertyName("tg_name")]
        public string? Tg_name { get; set; }
        [JsonPropertyName("merlion_name")]
        public string? Merlion_name { get; set; }
        [JsonPropertyName("id")]
        public string? Id { get; set; }
        [JsonPropertyName("ids")]
        public string? Ids { get; set; }
        [JsonPropertyName("color")]
        public string? Color { get; set; }
        [JsonPropertyName("color_code")]
        public string? Color_code { get; set; }
        [JsonPropertyName("memory")]
        public string? Memory { get; set; }
        [JsonPropertyName("external_memory")]
        public string? External_memory { get; set; }
        [JsonPropertyName("hardware_revision")]
        public string? Hardware_revision { get; set; }
        [JsonPropertyName("accessory_set_identifier")]
        public string? Accessory_set_identifier { get; set; }
        [JsonPropertyName("code")]
        public string? Code { get; set; }
        [JsonPropertyName("year")]
        public string? Year { get; set; }
        [JsonPropertyName("month")]
        public string? Month { get; set; }
        [JsonPropertyName("month_code")]
        public string? Month_code { get; set; }
        [JsonPropertyName("unique_number")]
        public string? Unique_number { get; set; }
        [JsonPropertyName("products_id")]
        public string? Products_id { get; set; }
        [JsonPropertyName("tg")]
        public string? Tg { get; set; }
        [JsonPropertyName("ncode")]
        public string? Ncode { get; set; }
        [JsonPropertyName("tags")]
        public string? Tags { get; set; }
        [JsonPropertyName("brand")]
        public string? Brand { get; set; }
        [JsonPropertyName("codecheck")]
        public string? Codecheck { get; set; }
        [JsonPropertyName("servicecode")]
        public string? Servicecode { get; set; }
        [JsonPropertyName("parser_mode")]
        public string? Parser_mode { get; set; }
        [JsonPropertyName("insp_id")]
        public string? Insp_id { get; set; }
    }

    public class Program
    {
        private static HttpClient? httpClient = null; /* WebRequest is obsolete */

        static async Task Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            if (args.Length <= 1)
            {
                PrintUsageInfo();
                return;
            }

            httpClient = new HttpClient();
            for (int i = 0; i < args.Length; i += 2)
            {
                try
                {
                    if (args[i].ToLower() == "-serial" && args[i + 1] != null)
                    {
                        await FindInfoBySerial(args[i + 1]);
                    }
                    else
                    {
                        PrintUsageInfo();
                    }
                }
                catch (IndexOutOfRangeException e)
                {
                    Console.WriteLine($"{args[i]}: Missing argument");
                    Console.WriteLine($"{e.Message}");
                    PrintUsageInfo();
                    return;
                }
            }

        }

        private static void PrintUsageInfo()
        {
            Console.WriteLine("\nUSAGE: ParseJSON.exe -Serial N12345H6F78901");
            Console.WriteLine("Press any key to close the window...");
            Console.ReadKey();
        }

        public static async Task FindInfoBySerial(string serialNumber)
        {
            var values = new Dictionary<string, string>
            {
                { "serial", serialNumber }
            };
            var content = new FormUrlEncodedContent(values);

            HttpResponseMessage? responseMessage = null;
            try
            {
                responseMessage = await httpClient.PostAsync("https://ippon.ru/support/help/serial.php", content);
            }
            catch (Exception e)
            {
                if (e is HttpRequestException || e is WebException)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"ERROR: {e.Message}");
                    Console.ResetColor();
                    Console.WriteLine("Press any key to close the window...");
                    Console.ReadKey();
                    return;
                }
            }
            _ = responseMessage.EnsureSuccessStatusCode();
            string responseBody = await responseMessage.Content.ReadAsStringAsync();

            JObject parsed = JObject.Parse(responseBody);
            foreach (var pair in parsed)
            {
                Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
            }

            UPSData? data;
            try
            {
                data = System.Text.Json.JsonSerializer.Deserialize<UPSData>(responseBody);

            }
            catch (NotSupportedException e)
            {
                Console.WriteLine(e.Message);
                return;
            }

            Console.WriteLine("***************************************");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Полное наименование: {data?.Full_name}");
            Console.WriteLine($"Артикул: {data?.Model}");
            Console.WriteLine($"Код: {data?.Id}");
            Console.WriteLine($"Серийный номер: {data?.Serial}");
            Console.WriteLine($"Ревизия: {data?.Hardware_revision}");
            Console.WriteLine($"Дата производства: {data?.Month} {data?.Year}");
            if (!string.Equals(data?.Status, "OK", StringComparison.OrdinalIgnoreCase))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"ERROR: {data?.Error}");
            }
            Console.ResetColor();
        }
    }
}

Вывод на экран должен быть примерно такой же как в случае с реализацией скрипта на PowerShell.



Подписаться
Уведомление о
guest
0 Комментарий
Inline Feedbacks
View all comments