C#对JSON文件进行增删改查

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace WebApi.Helper.Tool
{
    class JsonFileHelper
    {
        / 
        / 
        / 
        / 根目录的相对途径包含文件名
        //public JsonFileHelper(string jsonName = "appsettings", string _path = "appsettings.json")
        //{
        //    if (!jsonName.EndsWith(".json"))
        //    {
        //        _path = $"{jsonName}.json";
        //    }
        //    else
        //    {
        //        _path = jsonName;
        //    }
        //    if (!File.Exists(_path))
        //    {//不存在 创建一个json文件
        //        File.WriteAllText(_path, "{}");
        //    }
        //}

        /// 
        /// 读取Json返回实体对象
        /// 
        /// 
        public static T Read() => Read("");

        /// 
        /// 根据节点读取Json返回实体对象
        /// 
        /// 根节点
        /// 
        public static T Read(string section, string _path = "appsettings.json")
        {
            try
            {
                using (StreamReader file = new StreamReader(_path))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JToken secJt = JToken.ReadFrom(reader);
                    if (!string.IsNullOrWhiteSpace(section))
                    {//jObj[section].SelectToken("address").SelectToken("name")
                        string[] nodes = section.Split(':');
                        foreach (string node in nodes)
                        {
                            secJt = secJt[node];
                        }
                        if (secJt != null)
                        {
                            return JsonConvert.DeserializeObject(secJt.ToString());
                        }
                    }
                    else
                    {
                        return JsonConvert.DeserializeObject(secJt.ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return default(T);
        }

        /// 
        /// 读取Json返回集合
        /// 
        /// 
        public static List ReadList() => ReadList("");

        /// 
        /// 根据节点读取Json返回集合
        /// 
        /// 根节点
        /// 
        public static List ReadList(string section, string _path = "appsettings.json")
        {
            try
            {
                using (StreamReader file = new StreamReader(_path))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JToken secJt = JToken.ReadFrom(reader);
                        if (!string.IsNullOrWhiteSpace(section))
                        {
                            string[] nodes = section.Split(':');
                            foreach (string node in nodes)
                            {
                                secJt = secJt[node];
                            }
                            if (secJt != null)
                            {
                                return JsonConvert.DeserializeObject>(secJt.ToString());
                            }
                        }
                        else
                        {
                            return JsonConvert.DeserializeObject>(section.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return default(List);
        }

        /// 
        /// 写入文件
        /// 
        /// 自定义对象
        /// 
        public static bool Write(T t) => Write("", t);
        /// 
        /// 写入指定section文件
        /// 
        /// 自定义对象
        /// 
        public static bool Write(string section, T t, string _path = "appsettings.json")
        {
            try
            {
                JObject jObj;
                string json = JsonConvert.SerializeObject(t);
                if (string.IsNullOrWhiteSpace(section))
                {
                    jObj = JObject.Parse(json);
                }
                else
                {
                    using (StreamReader file = new StreamReader(_path))
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        try
                        {
                            jObj = (JObject)JToken.ReadFrom(reader);
                            jObj[section] = JObject.Parse(json);
                        }
                        catch (Exception ex)
                        {
                            jObj = JObject.Parse(json);
                        }
                    }
                }
                using (StreamWriter writer = new StreamWriter(_path))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
                    {
                        jObj.WriteTo(jsonWriter);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// 
        /// 删除或修改 单个节点
        /// 
        /// 节点途径 格式为A:B:C  如果节点带数组格式  A:[0]:C 数组用中括号
        /// 是删除还是修改
        /// 修改节点的内容
        /// 修改内容类型 数据:true  字符串:false
        private static bool JTokenHander(string section, bool isRemove, string value, bool isNum, string _path = "appsettings.json")
        {
            try
            {
                JToken jObj;
                using (StreamReader file = new StreamReader(_path))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObj = JToken.ReadFrom(reader);
                        string[] nodes = section.Split(':');
                        JToken tempToken = jObj;
                        if (nodes != null && nodes.Length > 0)
                        {
                            foreach (string node in nodes)
                            {
                                if (node != null)
                                {
                                    if (node.StartsWith("[") && node.EndsWith("]"))
                                    {
                                        int tempi = 0;
                                        if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
                                        {
                                            tempToken = tempToken[tempi];
                                        }
                                    }
                                    else
                                    {
                                        tempToken = tempToken[node];
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        if (tempToken != null)
                        {
                            if (isRemove)
                            {
                                if (tempToken.HasValues)
                                    tempToken.Remove();
                                else
                                    tempToken.Parent.Remove();
                            }
                            else
                            {
                                JToken token;
                                if (isNum)
                                {
                                    if (value.Contains("."))
                                    {
                                        double tempd;
                                        double.TryParse(value, out tempd);
                                        token = tempd;
                                    }
                                    else
                                    {
                                        int tempi = 0;
                                        int.TryParse(value, out tempi);
                                        token = tempi;
                                    }

                                }
                                else
                                {
                                    token = value;
                                }
                                tempToken.Replace(token);//改
                            }
                        }
                    }
                }
                using (StreamWriter writer = new StreamWriter(_path))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
                    {
                        Formatting = Formatting.Indented,//格式化缩进
                        Indentation = 4,  //缩进四个字符
                        IndentChar = ' '  //缩进的字符是空格
                    })
                    {
                        jObj.WriteTo(jsonWriter);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// 
        /// 添加/修改 单个节点
        /// 
        /// 
        public static bool JTokenHanderUpdate(Dictionary keyValuePairs, bool isTX = false, bool isT = true,  string _path = "appsettings.json")
        {
            try
            {
                JToken jObj;
                using (StreamReader file = new StreamReader(_path))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObj = JToken.ReadFrom(reader);
                        string[] nodes = keyValuePairs.Keys.FirstOrDefault().ToString().Split(':');
                        JToken tempToken = jObj;
                        foreach (string node in nodes)
                        {
                            if (node != null)
                            {
                                if (node.StartsWith("[") && node.EndsWith("]"))
                                {
                                    int tempi = 0;
                                    if (int.TryParse(node.Trim('[').Trim(']'), out tempi))
                                    {
                                        tempToken = tempToken[tempi];
                                    }
                                }
                                else
                                {
                                    tempToken = tempToken[node];
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        if (tempToken != null)
                        {
                            JToken token;
                            if (isT)
                            {
                                if (isTX)
                                {
                                    dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values.FirstOrDefault());
                                    dynamic request = JsonConvert.DeserializeObject(requests);
                                    token = request;
                                    tempToken.AddAfterSelf(token);//添
                                }
                                else
                                {
                                    dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values.FirstOrDefault());
                                    dynamic request = JsonConvert.DeserializeObject(requests);
                                    token = request;
                                    tempToken.Replace(token);//改
                                }
                            }
                            else
                            {
                                if (isTX)
                                {
                                    dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values);
                                    dynamic request = JsonConvert.DeserializeObject(requests);
                                    token = request;
                                    tempToken.AddAfterSelf(token);//添
                                }
                                else
                                {
                                    dynamic requests = JsonConvert.SerializeObject(keyValuePairs.Values);
                                    dynamic request = JsonConvert.DeserializeObject(requests);
                                    token = request;
                                    tempToken.Replace(token);//改
                                }
                            }
                        }
                    }
                }
                using (StreamWriter writer = new StreamWriter(_path))
                {
                    using (JsonTextWriter jsonWriter = new JsonTextWriter(writer)
                    {
                        Formatting = Formatting.Indented,//格式化缩进
                        Indentation = 4,  //缩进四个字符
                        IndentChar = ' '  //缩进的字符是空格
                    })
                    {
                        jObj.WriteTo(jsonWriter);
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        /// 
        /// 删除指定节点
        /// 
        /// 节点途径 格式为A:B:C  如果节点带数组格式  A:[0]:C 数组用中括号
        public static bool Remove(string section)
        {
            return JTokenHander(section, true, "", false);
        }
        /// 
        /// 修改指定节点内容
        /// 
        /// 节点途径 格式为A:B:C  如果节点带数组格式  A:[0]:C 数组用中括号
        /// 修改节点的内容
        /// 修改内容类型 数据:true  字符串:false
        public static bool Update(string section, string value)
        {
            return JTokenHander(section, false, value, false);
        }
        /// 
        /// 读取节点内容
        /// 
        /// 节点途径 格式为A:B:C  如果节点带数组格式  A:[0]:C 数组用中括号
        /// 
        public static string Read(string section, string _path = "appsettings.json")
        {
            try
            {
                JToken jObj;
                using (StreamReader file = new StreamReader(_path))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObj = JToken.ReadFrom(reader);
                        string[] nodes = section.Split(':');
                        JToken tempToken = jObj;
                        if (nodes != null && nodes.Length > 0)
                        {
                            foreach (string node in nodes)
                            {
                                if (node != null)
                                {
                                    if (node.StartsWith("[") && node.EndsWith("]"))
                                    {
                                        int tempi = 0;
                                        if (int.TryParse(node, out tempi))
                                        {
                                            tempToken = tempToken[tempi];
                                        }
                                    }
                                    else
                                    {
                                        tempToken = tempToken[node];
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        if (tempToken != null)
                        {
                            return tempToken.ToString();
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return "";
        }
    }
}

你可能感兴趣的:(c#,笔记)