欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

HttpClient来自官方的JSON扩展方法

程序员文章站 2022-12-09 15:48:41
System.Net.Http.Json Json的序列化和反序列化是我们日常常见的操作,通过 System.Net.Http.Json 我们可以用少量的代码实现上述操作.正如在github设计文档中所描述 Serializing and deserializing JSON payloads fr ......

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平均快了两倍,如果有兴趣相关基准测试可在这个文章中查阅

在.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