参考页面:

http://www.yuanjiaocheng.net/webapi/test-webapi.html

http://www.yuanjiaocheng.net/webapi/web-api-controller.html

http://www.yuanjiaocheng.net/webapi/config-webapi.html

http://www.yuanjiaocheng.net/webapi/web-api-route.html

http://www.yuanjiaocheng.net/webapi/parameter-binding.html

用于永久化对象,什么程序都行,依赖NewtonSoft。用于json序列化和反序列化。
 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace ConfigHandler
 {
     public class ConfigHandler<T>
         where T : class
     {
         const string SAVE_PATH = "jsonconfig/";
         /// <summary>
         /// 单例模式
         /// </summary>
         static T config;
         private ConfigHandler()
         {

         }
         /// <summary>
         /// 获取保存地址,默认是泛型参数T的类型名称
         /// </summary>
         /// <returns></returns>
         private static string GetSavePath()
         {
             if (!Directory.Exists(SAVE_PATH))
             {
                 Directory.CreateDirectory(SAVE_PATH);
             }
             return $"{SAVE_PATH}{typeof(T).ToString()}.json";
         }
         /// <summary>
         /// 保存配置
         /// </summary>
         public static void Save(T _config)
         {
             config = _config;
             string json = JsonConvert.SerializeObject(_config);
             try
             {
                 using (var sw = new StreamWriter(GetSavePath()))
                 {
                     sw.WriteAsync(json);
                 }

             }
             catch (Exception)
             {
                 throw;
             }
         }
         /// <summary>
         /// 获取配置信息
         /// </summary>
         /// <returns></returns>
         public static T Load()
         {
             if (config == null)
             {
                 string json = "";
                 try
                 {
                     using (var sr = new StreamReader(GetSavePath()))
                     {
                         json = sr.ReadToEnd();
                         if (json != "")
                         {
                             config = JsonConvert.DeserializeObject<T>(json);
                         }
                         else
                         {
                             config = null;
                         }
                     }
                 }
                 catch (Exception)
                 {
                     config = null;
                 }
             }
             return config;
         }

     }

 }

demo:

using ConfigHandler;
using ConsoleApplication1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyConfig config = new MyConfig();
            config = new MyConfig();
            config.name = "leiming";
            config.Age = ;
            config.Time = DateTime.Now;
            ConfigHandler<MyConfig>.Save(config);
            config = ConfigHandler<MyConfig>.Load();
            Console.WriteLine(config.ToString());
            Console.ReadKey();
        }
    }
    class MyConfig
    {
        public int Hello{get;set;}
        public string name { get; set; }
        public int Age { get; set; }
        public DateTime Time { get; set; }
        public override string ToString()
        {
            return $"Name={name},Age={Age},Time={Time.ToShortDateString()}";
        }
    }
}

C# 对象实例化 用json保存 泛型类 可以很方便的保存程序设置的更多相关文章

  1. C# 对象实例化 用json保存 泛型类 可以很方便的保存程序设置

    用于永久化对象,什么程序都行,依赖NewtonSoft.用于json序列化和反序列化. using Newtonsoft.Json; using System; using System.Collec ...

  2. .Net使用Newtonsoft.Json.dll(JSON.NET)对象序列化成json、反序列化json示例教程

    JSON作为一种轻量级的数据交换格式,简单灵活,被很多系统用来数据交互,作为一名.NET开发人员,JSON.NET无疑是最好的序列化框架,支持XML和JSON序列化,高性能,免费开源,支持LINQ查询 ...

  3. python对象转化为json串、json串转化为python串

    1.1. JSON简介: JavaScript Object Notation(JavaScript对象表示法) JSON是存储和交换文本信息的语法.类似XML JSON比XML更小.更快.更易解析 ...

  4. JVM总括四-类加载过程、双亲委派模型、对象实例化过程

    JVM总括四-类加载过程.双亲委派模型.对象实例化过程 目录:JVM总括:目录 一. 类加载过程 类加载过程就是将.class文件转化为Class对象,类实例化的过程,(User user = new ...

  5. Java技巧——将前端的对象数组通过Json字符串传到后端并转换为对象集合

    Java技巧——将前端的对象数组通过Json字符串传到后端并转换为对象集合 摘要:本文主要记录了如何将将前端的对象数组通过Json字符串传到后端,并在后端将Json字符串转换为对象集合. 前端代码 前 ...

  6. .NET(C#)中的DataSet、string、DataTable等对象转换成Json

    ConvertJson.cs类 using System; using System.Collections.Generic; using System.Text; using System.Data ...

  7. Newtonsoft.Json 把对象转换成json字符串

    var resultJson = new { records = rowCount, page = pageindex, //总页数=(总页数+页大小-1)/页大小 total = (rowCount ...

  8. JSON转换类(二)--List转换成Json、对象集合转换Json等

    #region List转换成Json /// <summary> /// List转换成Json /// </summary> public static string Li ...

  9. json 字符串转换成对象,对象转换成json字符串

    json   字符串转换成对象,对象转换成json字符串 前端: 方法一: parseJSON方法:   [注意jquery版本问题] var str = '{"name":&qu ...

随机推荐

  1. 【.net 深呼吸】细说CodeDom(8):分支与循环

    有人会问,为啥 CodeDom 不会生成 switch 语句,为啥没生成 while 语句之类.要注意,CodeDom只关心代码逻辑,而不是语法,语法是给写代码的人用的.如果用.net的“反编译”工具 ...

  2. Ignite性能测试以及对redis的对比

    测试方法 为了对Ignite做一个基本了解,做了一个性能测试,测试方法也比较简单主要是针对client模式,因为这种方法和使用redis的方式特别像.测试方法很简单主要是下面几点: 不作参数优化,默认 ...

  3. C# 注册 Windows 热键

    闲扯: 前几日,一个朋友问我如何实现按 F1 键实现粘贴(Ctrl+V)功能,百度了一个方法,发给他,他看不懂(已经是 Boss 的曾经的码农),我就做了个Demo给他参考.今日得空,将 Demo 整 ...

  4. Matlab 绘制三维立体图(以地质异常体为例)

    前言:在地球物理勘探,流体空间分布等多种场景中,定位空间点P(x,y,x)的物理属性值Q,并绘制三维空间分布图,对我们洞察空间场景有十分重要的意义. 1. 三维立体图的基本要件: 全空间网格化 网格节 ...

  5. WebAPi之SelfHost自创建证书启动Https疑难解惑及无法正确返回结果

    前言 话说又来需求了,之前对于在SelfHost中需要嵌套页面并操作为非正常需求,这回来正常需求了,客户端现在加了https,老大过来说WebAPi访问不了了,这是什么情况,我去试了试,还真是这个情况 ...

  6. android studio你可能忽视的细节——启动白屏?drawable和mipmap出现的意义?这里都有!!!

    android studio用了很久了,也不知道各位小伙伴有没有还在用eclipse的,如果还有,楼主真心推荐转到android studio来吧,毕竟亲儿子,你会知道除了启动速度稍微慢些,你找不到一 ...

  7. 修改session垃圾回收几率

    <?php //修改session垃圾回收几率 ini_set('session.gc_probability','1'); ini_set('session.gc_divisor','2'); ...

  8. jquery中的$(document).ready(function() {});

    当文档载入时执行function函数里的代码, 这部分代码主要声明,页面加载后 "监听事件" 的方法.例如: $(document).ready( $("a") ...

  9. 无法访问org.springframework.core.NestedRuntimeException 找不到org.springframework.core.NestedRuntimeException的类文件

    在学习springAOP时,出现如下异常: 无法访问org.springframework.core.NestedRuntimeException 找不到org.springframework.cor ...

  10. iOS app内存分析套路

    iOS app内存分析套路 Xcode下查看app内存使用情况有2中方法: Navigator导航栏中的Debug navigator中的Memory Instruments 一.Debug navi ...