记录操作Json的方法
class JsonHelper
{
public static void ObjectToJson<T>(T t, string path) where T : class
{
DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate))
{
formatter.WriteObject(stream, t);
}
}
public static T JsonToObject<T>(T t, string path) where T : class
{
DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
using (FileStream stream = new FileStream(path, FileMode.Open))
{
T result = formatter.ReadObject(stream) as T;
return result;
}
}
private static string GetFileContent(string filePath)
{
string result = "";
if (File.Exists(filePath))
{
result = File.ReadAllText(filePath);
}
return result;
}
public static T Deserialize<T>(T t, string path)
{
string fileContent = GetFileContent(path);
if (!string.IsNullOrWhiteSpace(fileContent))
{
t = JsonConvert.DeserializeObject<T>(fileContent);
}
return t;
}
public static T ReadJSON<T>(string path)
{
try
{
StreamReader streamReader = new StreamReader(path);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(streamReader.ReadToEnd());
streamReader.Close();
return (T)jsonObj;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return default;
}
public static void WriteJSON<T>(string path, T value)
{
try
{
var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
string output = JsonConvert.SerializeObject(value, Formatting.Indented, jsonSetting);
File.WriteAllText(path, output);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static void EditJSON<T>(string path, string key, T value)
{
try
{
var jsonSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
StreamReader streamReader = new StreamReader(path);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(streamReader.ReadToEnd());
jsonObj[key] = value;
streamReader.Close();
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented, jsonSetting);
File.WriteAllText(path, output);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
|