49 lines
1.1 KiB
C#
49 lines
1.1 KiB
C#
using Newtonsoft.Json;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
public static class JsonUtils
|
|
{
|
|
public static string ToJson<T>(this T obj)
|
|
{
|
|
string result = string.Empty;
|
|
try
|
|
{
|
|
result = JsonConvert.SerializeObject(obj, Formatting.Indented);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Log4net.WriteLine("JsonUtils.ToJson()", LogType.Error);
|
|
Log4net.WriteLine(e);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public static T? ToObject<T>(this string json) where T : class, new()
|
|
{
|
|
T? result = default(T);
|
|
try
|
|
{
|
|
result = JsonConvert.DeserializeObject<T>(json);
|
|
}
|
|
catch(Exception e)
|
|
{
|
|
Log4net.WriteLine("JsonUtils.ToObject()", LogType.Warn);
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public static T? DeepCopy<T>(this T obj) where T : class, new()
|
|
{
|
|
string originJson = obj.ToJson();
|
|
T? clone = ToObject<T>(originJson);
|
|
|
|
return clone;
|
|
}
|
|
}
|