using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;

namespace Infrastructure
{
    /// <summary>
    /// Json操作
    /// </summary>
    public static class Json
    {
        public static object ToJson(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject(Json);
        }
        public static string ToJson(this object obj)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static string ToJson(this object obj, string datetimeformats)
        {
            var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
            return JsonConvert.SerializeObject(obj, timeConverter);
        }
        public static T ToObject<T>(this string Json)
        {
            return Json == null ? default(T) : JsonConvert.DeserializeObject<T>(Json);
        }
        public static List<T> ToList<T>(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<List<T>>(Json);
        }
        public static DataTable ToTable(this string Json)
        {
            return Json == null ? null : JsonConvert.DeserializeObject<DataTable>(Json);
        }
        public static JObject ToJObject(this string Json)
        {
            return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace("&nbsp;", ""));
        }
        /// <summary>
        /// 转换成JToken
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static JToken ToJToken(this string str)
        {
            try
            {
                var jToken = (JToken)JsonConvert.DeserializeObject(str);
                return jToken;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 检查请求参数是否异常
        /// </summary>
        /// <param name="obj"></param>
        public static void CheckReqIsNull(this object obj)
        {
            if (obj == null) throw new Exception("数据异常，请检查输入信息是否正确。");
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<T> InitListData<T>(this List<T> list)
        {
            if (list == null) list = new List<T>();
            return list;
        }
    }
}
