HttpClient来自官方的JSON扩展方法
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
HttpClient来自官方的JSON扩展方法的更多相关文章
- swift 官方获取JSON 数据方法
var url = NSURL(string: "http://www.weather.com.cn/data/sk/101120501.html") var data = NSD ...
- Asp.Net MVC以 JSON传值扩展方法
Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下: DataContractJsonSerializer类: 该类在System.Runtime.Serializ ...
- 利用扩展方法重写JSON序列化和反序列化
利用.NET 3.5以后的扩展方法重写JSON序列化和反序列化,在代码可读性和可维护性上更加加强了. 首先是不使用扩展方法的写法 定义部分: /// <summary> /// JSON ...
- Asp.Net MVC以JSON传值扩展方法
Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下: DataContractJsonSerializer类: 该类在System.Runtime.Serializ ...
- jquery扩展方法(表单数据格式化为json对象)
1.jquery扩展方法(表单数据格式化为json对象) <script type="text/javascript"> // 将表单数据序列化为一个json对象,例如 ...
- MongoDB:利用官方驱动改装为EF代码风格的MongoDB.Repository框架 五 --- 为List<MongoDBRef>增加扩展方法
本次改动主要内容:为List<MongoDBRef>增加扩展方法 在MongoDB.Repository的使用过程中,发现在一个类中只定义一个List<MongoDBRef>是 ...
- JavaScript操作JSON的方法总结,JSON字符串转换为JSON对象
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生格式,这意 ...
- 从扩展方法到匿名方法再到LINQ
1.首先我们应该知道什么是扩展方法: 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样 ...
- 扩展方法解决LinqToSql Contains超过2100行报错问题
1.扩展方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...
随机推荐
- python第一次作业
import turtle turtle.pensize(2) turtle.pencolor("black") turtle.fillcolor("red") ...
- 适用于 macOS 下 2K 显示器开启 HiDPI 的简便解决方案
前阵子入手了一款2k的显示器用于mbp的拓展屏幕,但由于苹果系统的严格限制,只有在4K及以上显示器上才能开启自带的HiDPI进行缩放以达到retina显示屏的效果.2k显示器下的字体会偏小发虚,使用1 ...
- Session的常用方法
Session的常用方法 session对象主要用于属性操作和会话管理,常用方法如下: 1.public void setAttribute(String name,String value)设定指定 ...
- 后端程序员不得不会的 Nginx 转发匹配规则
整理了一些Java方面的架构.面试资料(微服务.集群.分布式.中间件等),有需要的小伙伴可以关注公众号[程序员内点事],无套路自行领取 一口气说出 9种 分布式ID生成方式,面试官有点懵了 面试总被问 ...
- shell编程之循环语句
for #! /bin/sh for FRUIT in apple banana pear; do echo "I like $FRUIT" done while #! /bin/ ...
- JDBC(二)
## 详解JDBC各个对象 1.DriverManager对象:驱动管理对象 * 功能: 1.注册驱动:告诉程序该使用哪个数据jar包 static void registerDriver(D ...
- BIT-Reverse Pairs
2019-12-17 11:07:02 问题描述: 问题求解: 本题可以看作是逆序数问题的强化版本,需要注意的是num[i] > 2 * num[j],这里有0和负数的情况. public in ...
- NLP interview
2019-08-26 17:19:58 1)聊实习项目 2)代码题,二维数组中的查找某个target 3)讲一些最能体现创新能力的工作,而不是一些工程上的实现 4)讲论文可以从哪些方面做创新点,文本生 ...
- [贪心,dp] 2019中国大学生程序设计竞赛(CCPC) - 网络选拔赛 Fishing Master (Problem - 6709)
题目:http://acm.hdu.edu.cn/showproblem.php?pid=6709 Fishing Master Time Limit: 2000/1000 MS (Java/Othe ...
- leetcode 每日签到 409. 最长回文串
题目: 最长回文串 给定一个包含大写字母和小写字母的字符串,找到通过这些字母构造成的最长的回文串. 在构造过程中,请注意区分大小写.比如 "Aa" 不能当做一个回文字符串. 注意: ...