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

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

  使用起来其实也很简单,就是有些地方要注意,比如在我们的对象实体中有中文的话,直接序列化时中文会被转换成编码格式,时间格式序列化时会被转成默认的格式等。

  下面就直接上Demo的代码了

using System;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var user = new User{
                Id= 1,
                Name = "张三李四",
                Gender = Gender.Male,
                Email="[email protected]",
                CreatedTime = DateTime.Now
            };

            JsonSerializerOptions options = new JsonSerializerOptions();
            options.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); //解决中文序列化被编码的问题
            options.Converters.Add(new DateTimeConverter()); //解决时间格式序列化的问题

            var serializeString = JsonSerializer.Serialize(user, options);
            Console.WriteLine(serializeString);

            User obj = JsonSerializer.Deserialize<User>(serializeString,options);

            Console.ReadLine();
        }
    }

    class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        [JsonConverter(typeof(JsonStringEnumConverter))] //解决枚举序列化时被转成数值的问题
        public Gender Gender { get; set; }

        public string Email { get; set; }

        public DateTime CreatedTime { get; set; }
    }

    enum Gender
    {
        Male,

        FaleMale
    }

    public class DateTimeConverter : JsonConverter<DateTime>
    {
        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.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

    public class DateTimeNullableConverter : JsonConverter<DateTime?>
    {
        public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            return string.IsNullOrEmpty(reader.GetString()) ? default(DateTime?) : DateTime.Parse(reader.GetString());
        }

        public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value?.ToString("yyyy-MM-dd HH:mm:ss"));
        }
    }

}

原文地址:https://www.cnblogs.com/jesen1315/p/12023760.html

时间: 2024-07-29 20:51:08

.net core中关于System.Text.Json的使用的相关文章

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

行为不一致 .NET Core 3.0 新出了个内置的 JSON 库, 全名叫做尼古拉斯 System.Text.Json - 性能更高占用内存更少这都不是事... 对我来说, 很多或大或小的项目能少个第三方依赖项, 还能规避多个依赖项的依赖 Newtonsoft.Json 版本不一致的问题, 是件极美的事情. 但是, 结果总不是不如预期那么简单和美好, 简单测试了下, 有一些跟 Newtonsoft.Json 行为不一致的地方, 代码如下: using Microsoft.VisualStud

Net core 2.x 升级 3.0 使用自带 System.Text.Json 时区 踩坑经历

.Net Core 3.0 更新的东西很多,这里就不多做解释了,官方和博园大佬写得很详细 关于 Net Core 时区问题,在 2.1 版本的时候,因为用的是 Newtonsoft.Json,配置比较方便 AddJsonOptions(opt => { opt.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local; }) 但是用 System.Text.Json 就没那么方便了,翻

ef core 自引用类 报错System.Text.Json.JsonException: A possible object cycle was detected which is not supported....

ef core 创建自引用灰了了 public class Menu:IEntity { public int Id { get; set; } public string text { get; set; } public bool group { get; set; } public bool shortout_root { get; set; } public string link { get; set; } public string icon { get; set; } public

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实现时间转换

在Asp.Net Core 3.0中如何使用 Newtonsoft.Json 库序列化数据

在.Net Core 3.0中 内置了一套Json序列化/反序列化方案,默认可以不再依赖,不再支持   Newtonsoft.Json. 但是.NET Core 3.0 System.Text.Json 和 Newtonsoft.Json 使用方法不一致,对于3.0以前版本升级有限制.如果前端代码以固定更没法用了. 在Asp.Net Core 3.0中如何使用  Newtonsoft.Json 库序列化数据 官方给出了兼容处理方案,操作步骤如下: 1.引用Microsoft.AspNetCore

浅析 .Net Core中Json配置的自动更新

Pre 很早在看 Jesse 的Asp.net Core快速入门的课程的时候就了解到了在Asp .net core中,如果添加的Json配置被更改了,是支持自动重载配置的,作为一名有着严重"造轮子"情节的程序员,最近在折腾一个博客系统,也想造出一个这样能自动更新以Mysql为数据源的ConfigureSource,于是点开了AddJsonFile这个拓展函数的源码,发现别有洞天,蛮有意思,本篇文章就简单地聊一聊Json config的ReloadOnChange是如何实现的,在学习Re

【转】TransactionScope事务处理方法介绍及.NET Core中的注意事项

什么是TransactionScope呢? TransactionScope作为System.Transactions的一部分被引入到.NET 2.0.同时SqlClient for .NET Core 从 2.1 及以上版本开始提供对System.Transactions的支持 . 它是一个类,它提供了一种简单的方法,可以将一组操作作为事务的一部分来进行处理,而不必担心场景背后的复杂性.如果某个操作在执行的过程中失败的话,则整个事务将失败并执行回滚操作,从而撤消已完成的所有操作.所有这些都将由

.NET Core在类库中读取配置文件appsettings.json

在.NET Framework框架时代我们的应用配置内容一般都是写在Web.config或者App.config文件中,读取这两个配置文件只需要引用System.Configuration程序集,分别用 System.Configuration.ConfigurationManager.AppSettings["SystemName"];//读取appSettings配置 System.Configuration.ConfigurationManager.ConnectionStrin

ServiceStack.Text json中序列化日期格式问题的解决

标记: ServiceStack.Text,json,序列化,日期 在使用ServiceStack.Text的序列化为json格式的时候,当属性为datetime的时候,返回的是一个new date(324234234)的字符串,看着非常不爽. 如果是js来获取结果还好, 如果是c#获取这种字符串是没有办法转化为时间的. 所以我改造了下,让返回的是'2015-06-06 09:11:11'的格式. 先获取源码, 然后在jsconfig.cs中加入如下代码 Code Snippet private