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

HttpClient来自官方的JSON扩展方法的更多相关文章

  1. swift 官方获取JSON 数据方法

    var url = NSURL(string: "http://www.weather.com.cn/data/sk/101120501.html") var data = NSD ...

  2. Asp.Net MVC以 JSON传值扩展方法

    Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下: DataContractJsonSerializer类: 该类在System.Runtime.Serializ ...

  3. 利用扩展方法重写JSON序列化和反序列化

    利用.NET 3.5以后的扩展方法重写JSON序列化和反序列化,在代码可读性和可维护性上更加加强了. 首先是不使用扩展方法的写法 定义部分: /// <summary>  /// JSON ...

  4. Asp.Net MVC以JSON传值扩展方法

    Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下: DataContractJsonSerializer类: 该类在System.Runtime.Serializ ...

  5. jquery扩展方法(表单数据格式化为json对象)

    1.jquery扩展方法(表单数据格式化为json对象) <script type="text/javascript"> // 将表单数据序列化为一个json对象,例如 ...

  6. MongoDB:利用官方驱动改装为EF代码风格的MongoDB.Repository框架 五 --- 为List<MongoDBRef>增加扩展方法

    本次改动主要内容:为List<MongoDBRef>增加扩展方法 在MongoDB.Repository的使用过程中,发现在一个类中只定义一个List<MongoDBRef>是 ...

  7. JavaScript操作JSON的方法总结,JSON字符串转换为JSON对象

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生格式,这意 ...

  8. 从扩展方法到匿名方法再到LINQ

    1.首先我们应该知道什么是扩展方法: 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样 ...

  9. 扩展方法解决LinqToSql Contains超过2100行报错问题

    1.扩展方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...

随机推荐

  1. scrapycrawl 爬取笔趣阁小说

    前言 第一次发到博客上..不太会排版见谅 最近在看一些爬虫教学的视频,有感而发,大学的时候看盗版小说网站觉得很能赚钱,心想自己也要搞个,正好想爬点小说能不能试试做个网站(网站搭建啥的都不会...) 站 ...

  2. numpy——>数组拼接np.concatenate

    语法:np.concatenate((a1, a2, ...), axis=0) 1.默认是 axis = 0,也就是说对0轴(行方向)的数组对象,进行其垂直方向(axis=1)的拼接(即数据整行整行 ...

  3. 微信公众号 H5页面 支付注意细节

    1.   当秘钥(AppSecretApplets) 有问题时注意是不是已经被重置过了,此时要注意获取最新的秘钥: 2.   调试时后端的东西要放在线上https 请求 不然在手机上测试时 会被拦截: ...

  4. 神器cut基因剪

    cut cut 不就是切嘛,没错就是它--我给他起了一个外号基因剪刀 来我们学一下怎么使用这个命令 cut --help [root@ESProbe ~]# cut --help Usage: cut ...

  5. Java中请优先使用try-with-resources而非try-finally

    Java中请优先使用try-with-resources而非try-finally Java库包含了很多需要手工调用close方法来关闭的资源.比如说InputStream.OutputStream及 ...

  6. 我的Keras使用总结(2)——构建图像分类模型(针对小数据集)

    Keras基本的使用都已经清楚了,那么这篇主要学习如何使用Keras进行训练模型,训练训练,主要就是“练”,所以多做几个案例就知道怎么做了. 在本文中,我们将提供一些面向小数据集(几百张到几千张图片) ...

  7. Swift4.1 新特性compactMap函数

    关于compactMap函数 苹果在Swift 4.1中新增compactMap函数,用来代替flatMap函数. 在Swift标准库中compactMap定义如下 public func compa ...

  8. Selenium系列(一) - 8种元素定位方式的详细解读

    安装Selenium和下载Driver 安装selenium pip3 install  selenium -i http://pypi.douban.com/simple --trusted-hos ...

  9. shellcode

    msf > use windows/exec msf > set CMD calc.exe msf > set EXITFUNC thread msf > generate - ...

  10. 参加Folding@Home(FAH)项目,为战胜新冠肺炎贡献出自己的一份力量

    鉴于新冠病毒(COVID-19)在全球范围内的大规模传播,PCMR和NVIDIA呼吁全球PC用户加入Folding@home项目贡献自己闲置的GPU计算力,协助抗击新冠状病毒疫情. 目前全球有超过40 ...