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 ...
随机推荐
- Spring Boot入门系列(六)如何整合Mybatis实现增删改查
前面介绍了Spring Boot 中的整合Thymeleaf前端html框架,同时也介绍了Thymeleaf 的用法.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/z ...
- JAVAEE学习day04方法的定义和重载
1.方法定义的格式 方法就是完成特定功能的代码块 修饰符 返回值类型 方法名(参数类型 参数名1, 参数类型 参数名2...){ 方法体; return 返回值; } 修饰符: 初学者只需记住publ ...
- LeetCode(239.滑动窗口的最大值
题目: 给定一个数组nums,有一个大小为k的滑动窗口从数组的最左侧移动到最右侧,你只可以看到滑动窗口内的k个数字.滑动窗口每次只向右移动一位. 返回滑动窗口中的最大值. 示例: 输入: nums = ...
- Struts UI标签的使用
先来看一下日期控件 html5标签中其实已经有日期的类型,用<input type="date">便可调用. struts里面也自带了日期控件,其使用步骤为: 1. 导 ...
- Centos7报Could not resolve host: mirrorlist.centos.org; Unknown error(VMware网络设置)
软件:VMware 12 Linux版本:centOS 7 网络设置:桥接模式 安装后ping百度网址时报错:Name or service not know,使用yum安装时报错:Could not ...
- Python接口测试(第一个接口返回的数据作为第二个参数的入参)
python代码如下 import requests url1="http://localhost:8080/pinter/com/getSku?id=1" respon=requ ...
- Proteomic Profiling of Paired Interstitial Fluids Reveals Dysregulated Pathways and Salivary NID1 as a Biomarker of Oral Cavity Squamous Cell Carcinoma (解读人:张聪敏)
文献名:Proteomic Profiling of Paired Interstitial Fluids Reveals Dysregulated Pathways and Salivary NID ...
- JAVA EE,JAVA SE,JAVA ME,JDK,JRE,JVM之间的区别
JAVA EE是开发企业级应用,主要针对web开发有一套解决方案. JAVA SE是针对普通的桌面开发和小应用开发. JAVA ME是针对嵌入式设备开发,如手机. JRE是程序的运行环境 JDK是程序 ...
- 深入Redis客户端(redis客户端属性、redis缓冲区、关闭redis客户端)
深入Redis客户端(redis客户端属性.redis缓冲区.关闭redis客户端) Redis 数据库采用 I/O 多路复用技术实现文件事件处理器,服务器采用单线程单进程的方式来处理多个客户端发送过 ...
- 单例模式和配置admin
单例模式和配置admin 单例模式的概念 单例模式主要目的是确保某一个类只有一个实例存在.比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信 ...