权术天下,上海英才进修学院,辛烷值测定仪
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平均快了两倍,如果有兴趣相关基准测试可在这个文章中查阅
目前它还是预览版本
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异常类处理相应的异常.
https://github.com/hueifeng/blogsample/tree/master/src/systemnethttpjson
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论