C Json序列化简单应用

C#使用json 点击工具- NuGet包管理器- 程序包管理控制台,输入下面命令: Install-Package Newtonsoft.Json 即可使用Newtonsoft.Json 包进行json操作

using Newtonsoft.Json;
using System;
using System.IO;
using System.Runtime.Serialization;

namespace HelpTool
{
	public class JsonSerialize
	{
		public int IntValue = 2;
		public double DoubleValue = 2.2;
		public string StringValue = "jsonTest";

		public int IntAttributes
		{
			get;
			set;
		} = 5;
		public double DoubleAttributes
		{
			get;
			set;
		} = 5.5;
		public string StringAttributes
		{
			get;
			set;
		} = "空值";
		public string[] ArrayString
		{
			get;
			set;
		} = new string[] { "空值1", "空值2", "空值3" };

		public StructValue StructV = new StructValue(new string[] { "结构1", "结构2", "结构3" }, 1, 1.1, "结构");

		public struct StructValue
		{
			public string[] ArrayString
			{
				get;
				set;
			}

			public int IntValue;
			public double DoubleValue;
			public string StringValue;

			public StructValue(string[] array, int i, double db, string str)
			{
				ArrayString = array;
				IntValue = i;
				DoubleValue = db;
				StringValue = str;
			}
		}

		/// <summary>
		/// 加载参数
		/// </summary>
		/// <param name="strName">硬件名称</param>
		/// <returns></returns>
		public static JsonSerialize Load(string strName)
		{
			JsonSerialize josnTest = new JsonSerialize();
			josnTest.StringValue = strName;
			string configFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", strName + "_Config.json");

			if (File.Exists(configFileName))
			{
				try
				{
					josnTest = JsonConvert.DeserializeObject<JsonSerialize>(File.ReadAllText(configFileName));
				}
				catch (SerializationException e)
				{
					Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
				}
			}

			return josnTest;
		}

		/// <summary>
		/// 保存参数
		/// </summary>
		/// <returns></returns>
		public bool Save()
		{
			try
			{
				string configFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", StringValue + "_Config.json"); ;
				File.WriteAllText(configFileName, JsonConvert.SerializeObject(this));
			}
			catch (Exception e)
			{
				Console.WriteLine("Failed to serialize. Reason: " + e.Message);
				return false;
			}
			return true;
		}
	}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值