• C#.NET官方类库Json序列化,反序列化


    NuGet:搜索System.Text.Json  安装

    引用:

    using System.Text.Encodings.Web;
    using System.Text.Json;
    using System.Threading.Tasks;
    using System.IO;

    序列化方法:

            private static JsonSerializerOptions serializerOptions = new JsonSerializerOptions() { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
            public static string JsonSerialize<T>(T obj) => JsonSerializer.Serialize(obj, serializerOptions);
            public static void JsonSerialize<T>(T obj, string fileName)
            {
                using (FileStream createStream = File.Create(fileName))
                {
                    JsonSerializer.Serialize(createStream, obj, serializerOptions);
                }
            }
            public static async Task JsonSerializeAsync<T>(T obj, string fileName)
            {
                using (FileStream createStream = File.Create(fileName))
                {
                    await JsonSerializer.SerializeAsync(createStream, obj, serializerOptions);
                }
            }

    反序列化方法:

            public static void JsonDeserialize<T>(string jsonString, out T obj) => obj = JsonSerializer.Deserialize<T>(jsonString);
            public static T JsonDeserialize<T>(string fileName) => JsonSerializer.Deserialize<T>(File.ReadAllText(fileName));
            public static async Task JsonDeserializeAsync<T>(string fileName)
            {
                using (FileStream openStream = File.OpenRead(fileName))
                {
                    await JsonSerializer.DeserializeAsync<T>(openStream);
                }
            }
  • 相关阅读:
    Mysql之主从复制
    Java之对象序列化和反序列化
    java URI 与URL问题
    java之路径
    Java学习之位运算和逻辑运算符
    设计模式之六大原则
    观察者模式与监听器
    动态代理
    git 本地分支与远程分支
    创建分支策略
  • 原文地址:https://www.cnblogs.com/momj/p/15701245.html
Copyright © 2020-2023  润新知