HttpClient来自官方的JSON扩展方法

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。HttpClient来自官方的JSON扩展方法,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

System.Net.Http.Json

Json的序列化和反序列化是我们日常常见的操作,通过System.Net.Http.Json我们可以用少量的代码实现上述操作.正如在github设计文档中所描述

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.

他的依赖项也非常的少目前只依赖System.Net.Http, System.Text.Json
System.Text.Json相对于Newtonsoftjson平均快了两倍,如果有兴趣相关基准测试可在这个文章中查阅
https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

在.NET中安装和使用

目前它还是预览版本

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

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

还可以以下面这种简洁方式使用

_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.");
    }
}

还可以通过NotSupportedException和JsonException异常类处理相应的异常.

Reference

https://github.com/hueifeng/BlogSample/tree/master/src/SYSTEMNETHTTPJSON

https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

https://github.com/dotnet/designs/blob/d4018c99c8134e9114a869e2e73a050059b9e663/accepted/2020/json-http-extensions/json-http-extentions.md

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/158563.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!