C# Json 序列化 反序列化

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Demo
{
    /// <summary>
    /// Json编码
    /// </summary>
    public class JsonEncode
    {
        /// <summary>
        /// Json反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <param name="ignoreError"></param>
        /// <returns></returns>
        public static T? JsonDeserialize<T>(string str, bool ignoreError = false)
        {
            try
            {
                if (!ignoreError)
                {
                    return JsonConvert.DeserializeObject<T>(str);
                }
                else
                {
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 忽略不存在的字段,设置为null
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
                    return JsonConvert.DeserializeObject<T>(str, serializerSettings);
                }
            }
            catch
            {
                return default;
            }
        }
        /// <summary>
        /// Json反序列化
        /// </summary>
        /// <param name="str"></param>
        /// <param name="type"></param>
        /// <param name="ignoreError"></param>
        /// <returns></returns>
        public static object? JsonDeserialize(string str, Type type, bool ignoreError = false)
        {
            try
            {
                if (!ignoreError)
                {
                    return JsonConvert.DeserializeObject(str, type);
                }
                else
                {
                    var serializerSettings = new JsonSerializerSettings
                    {
                        // 忽略不存在的字段,设置为null
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
                    return JsonConvert.DeserializeObject(str, type, serializerSettings);
                }
            }
            catch
            {
                return default;
            }
        }
        /// <summary>
        /// Json序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string JsonSerialize(object obj)
        {
            var serializerSettings = new JsonSerializerSettings
            {
                // 设置为驼峰命名
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            return JsonConvert.SerializeObject(obj, Formatting.None, serializerSettings);
        }
    }
}

 

posted @ 2023-08-16 11:56  Mr_Xul  阅读(92)  评论(0编辑  收藏  举报