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;
}
}
}