You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.1 KiB
C#
82 lines
2.1 KiB
C#
using Newtonsoft.Json;
|
|
using System;
|
|
using System.IO;
|
|
|
|
namespace Production_Oil.Common
|
|
{
|
|
public class JsonHelper
|
|
{
|
|
/// <summary>
|
|
/// 读取Json文件
|
|
/// </summary>
|
|
/// <param name="filePath">文件路径</param>
|
|
/// <returns></returns>
|
|
public static string ReadJsonFile(string filePath)
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(filePath))
|
|
{
|
|
throw new FileNotFoundException(filePath);
|
|
}
|
|
return File.ReadAllText(filePath);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 将实体类序列化字符串
|
|
/// </summary>
|
|
/// <typeparam name="T">实体类</typeparam>
|
|
/// <param name="t"></param>
|
|
/// <returns></returns>
|
|
public static string SerializeObject<T>(T t)
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.SerializeObject(t);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 将对象序列化为json格式
|
|
/// </summary>
|
|
/// <param name="obj">序列化对象</param>
|
|
/// <returns>json字符串</returns>
|
|
public static string SerializeObjct(object obj)
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.SerializeObject(obj);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return string.Empty;
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 解析JSON字符串生成对象实体
|
|
/// </summary>
|
|
/// <typeparam name="T">实体类</typeparam>
|
|
/// <param name="json">JSON字符串</param>
|
|
/// <returns></returns>
|
|
public static T JsonConvertObject<T>(string json)
|
|
{
|
|
try
|
|
{
|
|
return JsonConvert.DeserializeObject<T>(json);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
throw;
|
|
}
|
|
}
|
|
}
|
|
}
|