天津投入产出系统后端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

98 lines
2.7 KiB

using System;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace QMAPP.WinForm
{
public class JsonHelper
{
public static T ReadConfigFromFile<T>(string fileName) where T : new()
{
var t = new T();
var strData = FileHelper.ReadFile(fileName);
try
{
t = JsonConvert.DeserializeObject<T>(strData);
}
catch (Exception ex)
{
MessageHelper.ShowError($"配置文件{fileName}错误,请重新配置!{Environment.NewLine}{ex.Message}");
}
return t;
}
public static void WriteConfigToFile<T>(string fileName, T t) where T : new()
{
var strData = JsonConvert.SerializeObject(t, Formatting.Indented);
// MessageHelper.ShowInfo(strConfig);
FileHelper.WriteFile(fileName, strData);
}
private const string Format = "yyyy-MM-dd HH:mm:ss";
public static string EntityToJsonSingle<T>(T t)
{
var timeFormat = new IsoDateTimeConverter { DateTimeFormat = Format };
var strJson = JsonConvert.SerializeObject(t, Formatting.None, timeFormat);
return strJson;
}
public static string EntityToJson<T>(T t)
{
var list = new List<T> { t };
var strJson = ListToJson(list);
return strJson;
}
public static T JsonToEntity<T>(string strJson)
{
T t;
try
{
var list = JsonToList<T>(strJson);
t = list[0];
}
catch
{
t = JsonConvert.DeserializeObject<T>(strJson);
}
return t;
}
public static string ListToJson<T>(List<T> list)
{
var timeFormat = new IsoDateTimeConverter { DateTimeFormat = Format };
var strJson = JsonConvert.SerializeObject(list, Formatting.None, timeFormat);
return strJson;
}
public static List<T> JsonToList<T>(string strJson)
{
var list = JsonConvert.DeserializeObject<List<T>>(strJson);
return list;
}
public static string DataSetToJson(DataSet ds)
{
var strJson = "";
strJson = JsonConvert.SerializeObject(ds, Formatting.Indented);
return strJson;
}
public static DataSet JsonToDataSet(string strJson)
{
var ds = new DataSet();
ds = JsonConvert.DeserializeObject<DataSet>(strJson);
return ds;
}
}
}