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实现时间转换的更多相关文章

  1. [.Net Core 3.0+/.Net 5] System.Text.Json中时间格式化

    简介 .Net Core 3.0开始全新推出了一个名为System.Text.Json的Json解析库,用于序列化和反序列化Json,此库的设计是为了取代Json.Net(Newtonsoft.Jso ...

  2. .netcore3.0 System.Text.Json 日期格式化

    .netcore3.0 的json格式化不再默认使用Newtonsoft.Json,而是使用自带的System.Text.Json来处理. 理由是System.Text.Json 依赖更少,效率更高. ...

  3. .net core中关于System.Text.Json的使用

    在.Net Framework的时候序列化经常使用Newtonsoft.Json插件来使用,而在.Net Core中自带了System.Text.Json,号称性能更好,今天抽空就来捣鼓一下. 使用起 ...

  4. .NET Core 3.0 System.Text.Json 和 Newtonsoft.Json 行为不一致问题及解决办法

    行为不一致 .NET Core 3.0 新出了个内置的 JSON 库, 全名叫做尼古拉斯 System.Text.Json - 性能更高占用内存更少这都不是事... 对我来说, 很多或大或小的项目能少 ...

  5. 【译】System.Text.Json 的下一步是什么

    .NET 5.0 最近发布了,并带来了许多新特性和性能改进.System.Text.Json 也不例外.我们改进了性能和可靠性,并使熟悉 Newtonsoft.Json 的人更容易采用它.在这篇文章中 ...

  6. 在.Net Core 3.0中尝试新的System.Text.Json API

    .NET Core 3.0提供了一个名为System.Text.Json的全新命名空间,它支持reader/writer,文档对象模型(DOM)和序列化程序.在此博客文章中,我将介绍它如何工作以及如何 ...

  7. .NET Core 内置的 System.Text.Json 使用注意

    System.Text.Json 是 .NET Core 3.0 新引入的高性能 json 解析.序列化.反序列化类库,武功高强,但毕竟初入江湖,炉火还没纯青,使用时需要注意,以下是我们在实现使用中遇 ...

  8. c# System.Text.Json 精讲

    本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...

  9. .NET 5的System.Text.Json的JsonDocument类讲解

    本文内容来自我写的开源电子书<WoW C#>,现在正在编写中,可以去WOW-Csharp/学习路径总结.md at master · sogeisetsu/WOW-Csharp (gith ...

随机推荐

  1. c#数字图像处理(七)直方图匹配

    直方图匹配,又称直方图规定化,即变换原图的直方图为规定的某种形式的直方图,从而使两幅图像具有类似的色调和反差.直方图匹配属于非线性点运算. 直方图规定化的原理:对两个直方图都做均衡化,变成相同的归一化 ...

  2. ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'system.sysuser', bu

    问题:已经在settings.py文件中注册过app仍旧提示没有安装,并且使用makegirations命令时会抛出如下异常. ValueError: The field admin.LogEntry ...

  3. supervisor守护filebeat服务进程

    1.变更原因 部署安装supervisor进行filebeat守护及后面的各种服务进程守护可以用2.变更内容增加supervisor服务 3.变量时间:6月2号-6月3号4.变更风险评估:无风险4.1 ...

  4. Flutter 入门 --- 内部分享

    八月部门给分配的分享任务,由于项目太赶,推迟一个月. 选 Flutter 这个主题,是因为现在它慢慢流行起来了,而我却不了解,故而借此契机,上手试试. 简介 Flutter 是 Google 推出的跨 ...

  5. VC简单操作mysql

    #include <iostream> #include <winsock.h> #include <mysql.h> #pragma comment(lib, & ...

  6. List<E> 、Set<E>和Map<K,E>的简单应用

    题目一: 创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集. 代码: List_Test.ja ...

  7. android studio sqlite实际应用中存在的问题

    原项目已上传到github long f = dbdatabase.update("user", values, "id=?", new String[]{St ...

  8. HDU 6562 lovers 2018CCPC吉林H(线段树)

    题意: 初始n个空串,m个操作: 1.给[l,r]的所有字符串头尾加一个‘d’,将原字符串x变为dxd 2.求[l,r]所有字符串代表的数字之和mod 1e9+7 思路: 据说是硬核线段树.. 对于线 ...

  9. Why Oracle VIP can not be switched to original node ?

    Oracle RAC is an share everything database architecture. The article is how to check out why virtual ...

  10. cookie 笔记

    Cookie    “小甜点” Cookie的作用是与服务器进行交互,作为HTTP规范的一部分而存在 ,而Web Storage仅仅是为了在本地“存储”数据而生 用来记录:用户信息  计算机信息  浏 ...