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. ASP.net MVC 构建layui管理后台(构造基础仓储)<1>

    本文章为ASP.net MVC 构建layui管理后台,第一篇. 使用EF+ado.net 实体数据模型模式进行底层的数据库连接. 在项目添加一个类库Model 在类库Model上添加一个ado.ne ...

  2. 学习 CSS 之用 CSS 3D 实现炫酷效果

    一.前言 把大象关进冰箱需要几步?三步,把冰箱门打开,把大象关进去,把冰箱门关上. 用 CSS 实现 3D 效果需几步?三步,设置透视效果 perspective,改变元素载体为 preserve-3 ...

  3. Ubuntu18.04 从头开始编译 Android Native WebRTC

    本文详细记录Mac下使用PD虚拟机安装ubuntu18.4桌面版,编译Android Native WebRTC的过程. 注意如果仅仅是使用WebRTC没必要手动编译源码,直接用官方提供的预编译包即可 ...

  4. @on-row-click="$emit('on-row-click', arguments[0], arguments[1])" 行内返回事件的一种写法

    @on-row-click="$emit('on-row-click', arguments[0], arguments[1])"

  5. node.js中http.respone.end方法概述

    方法说明: 结束响应,告诉客户端所有消息已经发送.当所有要返回的内容发送完毕时,该函数必须被调用一次. 如果不调用该函数,客户端将永远处于等待状态. 语法: response.end([data], ...

  6. vs2017 dlib19.3 opencv3.41 C++ 环境配置 人脸特征点识别

    身为一个.net程序员经过两天的采坑终于把人脸特征检测的项目跑通了,然后本文将以dlib项目中人脸特征检测工程为例,讲解dlib与opencv 在vs2017 C++ 项目中的编译与运行路径配置. 1 ...

  7. 【Weiss】【第03章】练习3.22、3.23、3.24:无代码题,栈的思考题

    [练习3.22] a.提出支持栈的Push和Pop操作以及第三种操作FindMin的数据结构,其中FindMin 返回该数据结构的最小元素,所有操作在最坏情况下的运行时间都是O(1). b.证明,如果 ...

  8. 网络安全从入门到精通(第一章-1)Web服务器通信原理

    本文内容 IP地址 域名 端口 HTTP协议 从访客角度看网页浏览器流程 常见服务器系统 路径 Web容器 常见的Web容器 !!!多动手,多动手,只看只听是不行的!!! 1,IP地址:就是计算机在互 ...

  9. C 2012年笔试题

    1指出程序段中的错误:分析错误的原因,并进行修改 1.1函数 swap 将两个字符串(字符数组作实参,长度不超过 100)的内容进行交换 void swap(char *pa,char *pb) { ...

  10. pywin32解析office文档

    from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = ...