.net core 中对象转json以及反序列化

先安装 Newtonsoft.Json 包

public class JsonHelper
    {
        /// <summary>
        /// 将实体类序列化为JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string SerializeJson<T>(T data)
        {
            return JsonConvert.SerializeObject(data);
        }
       
/// <summary>
        /// 反序列化json
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T DeserializeJson<T>(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static long ConvertToTimeStamp(DateTime time)
        {
            DateTime dateTime = new DateTime(1993, 1, 2, 3, 4, 5, DateTimeKind.Utc);
            return (long)(time.AddHours(-8) - dateTime).TotalMilliseconds;
        }
    }

 

    /// <summary>
    /// 系统扩展方法
    /// </summary>
    public static class SystemExtend
    {
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
    }

 数据转换为字符串可以用

Join<T>(String separator, IEnumerable<T> values);

 

posted @ 2020-06-20 22:24  青兰柳  阅读(5218)  评论(0编辑  收藏  举报