System.Net.Http.JsonJson的序列化和反序列化是我們?nèi)粘3R?jiàn)的操作,通過(guò)System.Net.Http.Json我們可以用少量的代碼實(shí)現(xiàn)上述操作.正如在github設(shè)計(jì)文檔中所描述 Serializing and deserializing JSON payloads from the network is a very common operation for clients, especially in the upcoming Blazor environment. Right now, sending a JSON payload to the server requires multiple lines of code, which will be a major speed bump for those customers. We'd like to add extension methods on top of HttpClient that allows doing those operations with a single method call. 他的依賴(lài)項(xiàng)也非常的少目前只依賴(lài)System.Net.Http, System.Text.Json 在.NET中安裝和使用目前它還是預(yù)覽版本 dotnet add package System.Net.Http.Json public static async Task<Customer> GetCustomerAsync()
{
HttpClient clinet=new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5000/customers");
var response = await clinet.SendAsync(request);
return await response.Content.ReadFromJsonAsync<Customer>();
}通過(guò)ReadFromJsonAsync直接可以反序列化 public static async Task<Customer> CreateCustomerAsync()
{
HttpClient clinet = new HttpClient();
var customer=new Customer()
{
Id = "1",
Name = "Fh"
};
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/create");
request.Content = JsonContent.Create(customer);
var response = await clinet.SendAsync(request);
var content=response.Content.ReadAsStringAsync();
return customer;
}還可以以下面這種簡(jiǎn)潔方式使用 _client.GetFromJsonAsync<IReadOnlyList<Customer>>("/customers");
_client.GetFromJsonAsync<Customer?>($"/customers/{id}");
_client.PutAsJsonAsync($"/customers/{customerId}", customer);if (response.IsSuccessStatusCode)
{
try
{
return await response.Content.ReadFromJsonAsync<User>();
}
catch (NotSupportedException) // When content type is not valid
{
Console.WriteLine("The content type is not supported.");
}
catch (JsonException) // Invalid JSON
{
Console.WriteLine("Invalid JSON.");
}
}還可以通過(guò)NotSupportedException和JsonException異常類(lèi)處理相應(yīng)的異常. Referencehttps://github.com/hueifeng/BlogSample/tree/master/src/SYSTEMNETHTTPJSON https://www./sending-and-receiving-json-using-httpclient-with-system-net-http-json |
|
|
來(lái)自: 路人甲Java > 《待分類(lèi)》