zoukankan      html  css  js  c++  java
  • NetCore 对Json文件的读写操作

    nuget

    Microsoft.Extensions.Configuration;
    Microsoft.Extensions.Configuration.Json;
    Newtonsoft.Json;
    Newtonsoft.Json.Linq;
        /// <summary>
        /// Json文件读写
        /// 引用Newtonsoft.Json
        /// </summary>
        public class JsonFileHelper
        {
            //注意:section为根节点
            private string _jsonName;
            private string _path;
            private IConfiguration Configuration { get; set; }
            public JsonFileHelper(string jsonName)
            {
                _jsonName = jsonName;
                if (!jsonName.EndsWith(".json"))
                    _path = $"{jsonName}.json";
                else
                    _path = jsonName;
                //ReloadOnChange = true 当*.json文件被修改时重新加载            
                Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = _path, ReloadOnChange = true, Optional = true })
                .Build();
            }
    
            /// <summary>
            /// 读取Json返回实体对象
            /// </summary>
            /// <returns></returns>
            public T Read<T>() => Read<T>("");
    
            /// <summary>
            /// 根据节点读取Json返回实体对象
            /// </summary>
            /// <returns></returns>
            public T Read<T>(string section)
            {
                try
                {
                    using (var file = new StreamReader(_path))
                    using (var reader = new JsonTextReader(file))
                    {
                        var jObj = (JObject)JToken.ReadFrom(reader);
                        if (!string.IsNullOrWhiteSpace(section))
                        {
                            var secJt = jObj[section];
                            if (secJt != null)
                            {
                                return JsonConvert.DeserializeObject<T>(secJt.ToString());
                            }
                        }
                        else
                        {
                            return JsonConvert.DeserializeObject<T>(jObj.ToString());
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
                return default(T);
            }
    
            /// <summary>
            /// 读取Json返回集合
            /// </summary>
            /// <returns></returns>
            public List<T> ReadList<T>() => ReadList<T>("");
    
            /// <summary>
            /// 根据节点读取Json返回集合
            /// </summary>
            /// <returns></returns>
            public List<T> ReadList<T>(string section)
            {
                try
                {
                    using (var file = new StreamReader(_path))
                    using (var reader = new JsonTextReader(file))
                    {
                        var jObj = (JObject)JToken.ReadFrom(reader);
                        if (!string.IsNullOrWhiteSpace(section))
                        {
                            var secJt = jObj[section];
                            if (secJt != null)
                            {
                                return JsonConvert.DeserializeObject<List<T>>(secJt.ToString());
                            }
                        }
                        else
                        {
                            return JsonConvert.DeserializeObject<List<T>>(jObj.ToString());
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }
                return default(List<T>);
            }
    
            /// <summary>
            /// 写入文件
            /// </summary>
            /// <typeparam name="T">自定义对象</typeparam>
            /// <param name="t"></param>
            public void Write<T>(T t) => Write("", t);
    
            /// <summary>
            /// 写入指定section文件
            /// </summary>
            /// <typeparam name="T">自定义对象</typeparam>
            /// <param name="t"></param>
            public void Write<T>(string section, T t)
            {
                try
                {
                    JObject jObj;
                    using (StreamReader file = new StreamReader(_path))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObj = (JObject)JToken.ReadFrom(reader);
                        var json = JsonConvert.SerializeObject(t);
                        if (string.IsNullOrWhiteSpace(section))
                            jObj = JObject.Parse(json);
                        else
                            jObj[section] = JObject.Parse(json);
                    }
    
                    using (var writer = new StreamWriter(_path))
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        jObj.WriteTo(jsonWriter);
                    }
                }
                catch (System.Exception ex)
                {
    
                    throw ex;
                }
            }
    
            /// <summary>
            /// 删除指定section节点
            /// </summary>
            /// <param name="section"></param>
            public void Remove(string section)
            {
                try
                {
                    JObject jObj;
                    using (StreamReader file = new StreamReader(_path))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObj = (JObject)JToken.ReadFrom(reader);
                        jObj.Remove(section);
                    }
    
                    using (var writer = new StreamWriter(_path))
                    using (var jsonWriter = new JsonTextWriter(writer))
                    {
                        jObj.WriteTo(jsonWriter);
                    }
                }
                catch (System.Exception ex)
                {
    
                    throw ex;
                }
            }
        }
  • 相关阅读:
    ansible用普通用户执行root权限的命令 + script模块
    screen 实用操作
    Kibana did not load properly
    1500元让我写一个api接口!没问题
    python实现四种出行路线规划(公交、步行、驾车、骑行)
    35行代码下载任意网页的图片
    Comparison of long-read sequencing technologies in the hybrid assembly of complex bacterial genomes
    A single-molecule long-read survey of the human transcriptome
    Long-read sequencing and de novo assembly of a Chinese genome 一个中国人基因组的长读测序和重新组装
    Combination of short-read, long-read, and optical mapping assemblies reveals large-scale tandem repeat arrays with population genetic implications
  • 原文地址:https://www.cnblogs.com/pingming/p/11171825.html
Copyright © 2011-2022 走看看