System.Text.Json 自定义Converter实现时间转换
Newtonsoft.Json与System.Text.Json区别
在 Newtonsoft.Json中可以使用例如
.AddJsonOptions(options =>
{
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
})
方式设置接收/序列化时间格式,但在.net core 3.1中System.Text.Json是没有自带方式进行转换,这就需要自定义Converter实现时间转换
官方GitHub地址

自定义DateTimeJsonConverter
public class DateTimeJsonConverter : JsonConverter<DateTime>
{
private readonly string _dateFormatString;
public DateTimeJsonConverter()
{
_dateFormatString = "yyyy-MM-dd HH:mm:ss";
}
public DateTimeJsonConverter(string dateFormatString)
{
_dateFormatString = dateFormatString;
}
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToUniversalTime().ToString(_dateFormatString));
}
}
JsonTokenType枚举类型共有以下几种
/// <summary>Defines the various JSON tokens that make up a JSON text.</summary>
public enum JsonTokenType : byte
{
/// <summary>There is no value (as distinct from <see cref="F:System.Text.Json.JsonTokenType.Null" />).</summary>
None,
/// <summary>The token type is the start of a JSON object.</summary>
StartObject,
/// <summary>The token type is the end of a JSON object.</summary>
EndObject,
/// <summary>The token type is the start of a JSON array.</summary>
StartArray,
/// <summary>The token type is the end of a JSON array.</summary>
EndArray,
/// <summary>The token type is a JSON property name.</summary>
PropertyName,
/// <summary>The token type is a comment string.</summary>
Comment,
/// <summary>The token type is a JSON string.</summary>
String,
/// <summary>The token type is a JSON number.</summary>
Number,
/// <summary>The token type is the JSON literal true.</summary>
True,
/// <summary>The token type is the JSON literal false.</summary>
False,
/// <summary>The token type is the JSON literal null.</summary>
Null,
}
services.AddMvc 中 Newtonsoft.Json与System.Text.Json 配置区别
.netcore 2.1
services
//全局配置Json序列化处理
.AddJsonOptions(options =>
{
//忽略循环引用
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//不使用驼峰样式的key
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
//设置时间格式
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
})
.netcore 3.1
services.AddControllers()
.AddJsonOptions(options =>
{
//设置时间格式
options.JsonSerializerOptions.Converters.Add(new DateTimeJsonConverter("yyyy-MM-dd HH:mm:ss"));
//设置bool获取格式
options.JsonSerializerOptions.Converters.Add(new BoolJsonConverter());
//不使用驼峰样式的key
options.JsonSerializerOptions.PropertyNamingPolicy = null;
//不使用驼峰样式的key
options.JsonSerializerOptions.DictionaryKeyPolicy = null;
//获取或设置要在转义字符串时使用的编码器
options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
});
bool型转换问题
.netcore 3.1中接收的json中不能将 "true"/"false"识别为boolean的True/False,这也需要自定义Converter实现bool转换
namespace Kdniao.Core.Utility
{
public class BoolJsonConverter : JsonConverter<bool>
{
public override bool Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False)
return reader.GetBoolean();
return bool.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, bool value, JsonSerializerOptions options)
{
writer.WriteBooleanValue(value);
}
}
}
System.Text.Json 自定义Converter实现时间转换的更多相关文章
- [.Net Core 3.0+/.Net 5] System.Text.Json中时间格式化
简介 .Net Core 3.0开始全新推出了一个名为System.Text.Json的Json解析库,用于序列化和反序列化Json,此库的设计是为了取代Json.Net(Newtonsoft.Jso ...
- .netcore3.0 System.Text.Json 日期格式化
.netcore3.0 的json格式化不再默认使用Newtonsoft.Json,而是使用自带的System.Text.Json来处理. 理由是System.Text.Json 依赖更少,效率更高. ...
- .net core中关于System.Text.Json的使用
在.Net Framework的时候序列化经常使用Newtonsoft.Json插件来使用,而在.Net Core中自带了System.Text.Json,号称性能更好,今天抽空就来捣鼓一下. 使用起 ...
- .NET Core 3.0 System.Text.Json 和 Newtonsoft.Json 行为不一致问题及解决办法
行为不一致 .NET Core 3.0 新出了个内置的 JSON 库, 全名叫做尼古拉斯 System.Text.Json - 性能更高占用内存更少这都不是事... 对我来说, 很多或大或小的项目能少 ...
- 【译】System.Text.Json 的下一步是什么
.NET 5.0 最近发布了,并带来了许多新特性和性能改进.System.Text.Json 也不例外.我们改进了性能和可靠性,并使熟悉 Newtonsoft.Json 的人更容易采用它.在这篇文章中 ...
- 在.Net Core 3.0中尝试新的System.Text.Json API
.NET Core 3.0提供了一个名为System.Text.Json的全新命名空间,它支持reader/writer,文档对象模型(DOM)和序列化程序.在此博客文章中,我将介绍它如何工作以及如何 ...
- .NET Core 内置的 System.Text.Json 使用注意
System.Text.Json 是 .NET Core 3.0 新引入的高性能 json 解析.序列化.反序列化类库,武功高强,但毕竟初入江湖,炉火还没纯青,使用时需要注意,以下是我们在实现使用中遇 ...
- c# System.Text.Json 精讲
本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...
- .NET 5的System.Text.Json的JsonDocument类讲解
本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...
随机推荐
- Bate冲刺博客(3次)
Bate冲刺博客 课程介绍 课程 (https://edu.cnblogs.com/campus/xnsy/GeographicInformationScience) 作业要求 https://www ...
- js原型链和原型链的继承
每一个对象都有一个“_proto_”指针,指向实例化该对象的构造函数的原型对象,当该对象没有你想拿到的属性时,解释器会顺着指针不断向上找. 每一个构造你函数都有一个“prototype”属性,指向该构 ...
- 简单实现Android手机“全局可调试”(ro.debuggable = 1)的方法【锤子坚果3】
在Android真机上调试程序有一个前提,就是这个apk包必须有 debuggable=true 的属性才行.而除了自己开发的apk能够控制打包属性之外,其他的程序发行之后显然不会设这个值为 true ...
- Spring框架学习笔记(8)——spring boot+mybatis plus+mysql项目环境搭建
之前写的那篇Spring框架学习笔记(5)--Spring Boot创建与使用,发现有多小细节没有提及,,正好现在又学习了mybatis plus这款框架,打算重新整理一遍,并将细节说清楚 1.通过I ...
- ios--->const 用法总结
const 用法总结 宏.变量.常量区分 宏:只是在预处理器里进行文本替换,没有类型,不做任何类型检查,编译器可以对相同的字符串进行优化.只保存一份到 .rodata 段.甚至有相同后缀的字符串也可以 ...
- Java:线程的六种状态及转化
目录 Java:线程的六种状态及转化 一.新建状态(NEW) 二.运行状态(RUNNABLE) 就绪状态(READY) 运行状态(RUNNING) 三.阻塞状态(BLOCKED) 四.等待状态(WAI ...
- Django自动化测试平台项目案例
引言 在项目组待了近半年时间,根据自己的感受和体验,做了一个辅助测试的工具(数据预报平台),主要目的是针对目前项目接口文档缺失,自动化预报脚本无法可视化,资源循环利用,统一管理化. 业务背景 我们项目 ...
- Java properties文件集
log4j: log4j.rootLogger=info, console, log, error ###Console ### log4j.appender.console = org.apache ...
- Codeforces_490_E
http://codeforces.com/problemset/problem/490/E dfs,过程要注意细节,特别是当前位置取了与上个数当前位置相同是,若后面不符合条件,则当前位置要重置'?' ...
- HDU6440 Dream(费马小定理+构造) -2018CCPC网络赛1003
题意: 给定素数p,定义p内封闭的加法和乘法,使得$(m+n)^p=m^p+n^p$ 思路: 由费马小定理,p是素数,$a^{p-1}\equiv 1(mod\;p)$ 所以$(m+n)^{p}\eq ...