using Newtonsoft.Json;

using System.Collections.Generic;
using System.IO;

namespace Common.system
{
    public class JsonHelper
    {
        #region Method

        /// <summary>
        /// 类对像转换成json格式
        /// </summary>
        /// <returns></returns>
        public static string ToJson(object t)
        {
            return JsonConvert.SerializeObject(
                t, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include }
                );
        }
        /// <summary>
        /// 类对像转换成json格式
        /// </summary>
        /// <param name="t"></param>
        /// <param name="HasNullIgnore">是否忽略NULL值</param>
        /// <returns></returns>
        public static string ToJson(object t, bool HasNullIgnore)
        {
            if (HasNullIgnore)
            {
                return JsonConvert.SerializeObject(t, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
            }
            else
            {
                return ToJson(t);
            }
        }

        /// <summary>
        /// json格式转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strJson"></param>
        /// <returns></returns>
        public static T JsonToObj<T>(string strJson) where T : class
        {
            if (strJson != null && strJson != "") { return JsonConvert.DeserializeObject<T>(strJson); }

            return null;
        }

        internal static List<T> JsonToList<T>(string respstr)
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(respstr);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }

        #endregion Method
    }
}
