using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace Win.Utils
{
public static class SerializeExtensions
{
///
/// 实体对象转JSON字符串
///
///
///
///
public static string ToJson(this object obj, bool ignoreNull = false)
{
var options = new JsonSerializerOptions()
{
IgnoreNullValues = ignoreNull,
Converters = { new DateTimeConverterUsingDateTimeParse() },
};
return JsonSerializer.Serialize(obj, options);
}
///
/// JSON字符串转实体对象
///
///
///
///
public static T FromJson(this string jsonStr)
{
return string.IsNullOrEmpty(jsonStr) ? default : JsonSerializer.Deserialize(jsonStr);
}
///
/// 字符串序列化成字节序列
///
///
///
public static byte[] SerializeUtf8(this string str)
{
return str == null ? null : Encoding.UTF8.GetBytes(str);
}
///
/// 字节序列序列化成字符串
///
///
///
public static string DeserializeUtf8(this byte[] stream)
{
return stream == null ? null : Encoding.UTF8.GetString(stream);
}
///
/// JSON字符串转List<实体对象>
///
///
///
///
public static List FromListJson(this string jsonStr)
{
return JsonSerializer.Deserialize>(jsonStr);
}
}
}