JSON扩展类——JsonHelper
1.引用Newtonsoft.Json库(JSON.NET)。
2.复制粘贴JsonHelper吧。
源代码:
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Allen.Core { public static partial class JsonHelper { #region Private fields private static readonly JsonSerializerSettings JsonSettings; private const string EmptyJson = "[]"; #endregion #region Constructor static JsonHelper() { var datetimeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; JsonSettings = new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; JsonSettings.Converters.Add(datetimeConverter); } #endregion #region Public Methods /// <summary> /// 应用Formatting.None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 /// </summary> /// <param name="obj">任意一个对象</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <returns>标准的JSON格式的字符串</returns> public static string ToJson(object obj, JsonSerializerSettings jsonSettings) { return ToJson(obj, Formatting.None, jsonSettings); } /// <summary> /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 /// </summary> /// <param name="obj">任意一个对象</param> /// <param name="format">指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <returns>标准的JSON格式的字符串</returns> public static string ToJson(object obj, Formatting format, JsonSerializerSettings jsonSettings) { try { return obj == null ? EmptyJson : JsonConvert.SerializeObject(obj, format, jsonSettings ?? JsonSettings); } catch (Exception) { //TODO LOG return EmptyJson; } } /// <summary> /// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。</para> /// <para>转换失败,或发生其它异常,则返回dynamic对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <returns>dynamic对象</returns> public static dynamic FromJson(this string json, JsonSerializerSettings jsonSettings) { return FromJson<dynamic>(json, Formatting.None, jsonSettings); } /// <summary> /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。</para> /// <para>转换失败,或发生其它异常,则返回dynamic对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <param name="format">指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <returns>dynamic对象</returns> public static dynamic FromJson(this string json, Formatting format, JsonSerializerSettings jsonSettings) { return FromJson<dynamic>(json, format, jsonSettings); } /// <summary> /// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。</para> /// <para>转换失败,或发生其它异常,则返回T对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <typeparam name="T">反序列化对象的类型</typeparam> /// <returns></returns> public static T FromJson<T>(string json, JsonSerializerSettings jsonSettings) where T : class, new() { return FromJson<T>(json, Formatting.None, jsonSettings); } /// <summary> /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。</para> /// <para>转换失败,或发生其它异常,则返回T对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <param name="format">指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项</param> /// <param name="jsonSettings">在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置</param> /// <typeparam name="T">反序列化对象的类型</typeparam> /// <returns></returns> public static T FromJson<T>(string json, Formatting format, JsonSerializerSettings jsonSettings) where T : class, new() { T result; if (jsonSettings == null) { jsonSettings = JsonSettings; } try { result = string.IsNullOrWhiteSpace(json) ? default(T) : JsonConvert.DeserializeObject<T>(json, jsonSettings); } catch (JsonSerializationException) //在发生该异常后,再以集合的方式重试一次. { //LOG try { var array = JsonConvert.DeserializeObject<IEnumerable<T>>(json, jsonSettings); result = array.FirstOrDefault(); } catch (Exception) { //LOG result = default(T); } } catch (Exception) { //LOG result = default(T); } return result; } #endregion #region Public Extend Methods /// <summary> /// 反序列化JSON数据为dynamic对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。</para> /// <para>转换失败,或发生其它异常,则返回dynamic对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <returns>dynamic对象</returns> public static dynamic FromJson(this string json) { return FromJson<dynamic>(json, Formatting.None, JsonSettings); } /// <summary> /// 反序列化JSON数据到指定的.NET类型对象 /// <para>如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。</para> /// <para>转换失败,或发生其它异常,则返回T对象的默认值</para> /// </summary> /// <param name="json">需要反序列化的JSON字符串</param> /// <typeparam name="T">反序列化对象的类型</typeparam> /// <returns></returns> public static T FromJson<T>(this string json) where T : class, new() { return FromJson<T>(json, Formatting.None, JsonSettings); } /// <summary> /// 应用默认的Formatting枚举值None和默认的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 /// </summary> /// <param name="obj">任意一个对象</param> /// <returns>标准的JSON格式的字符串</returns> public static string ToJson(this object obj) { return ToJson(obj, Formatting.None, JsonSettings); } public static string ToJson<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); } public static string ToJson<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, Func<TSource, int, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate, Func<TSource, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate, Func<TSource, int, TResult> selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } #endregion #region Private Methods /// <summary> /// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 /// </summary> /// <typeparam name="TSource"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="source">需要转换为JSON格式字符串的对象</param> /// <param name="func">集合/数组条件筛选方法委托,返回筛选后的集合/数组</param> /// <param name="isFilterNull">是否过滤IEnumerable<TSource> source中的null对象,默认为true</param> /// <returns>标准的JSON格式的字符串</returns> private static string DelegateToJson<TSource, TResult>(IEnumerable<TSource> source, Func<TSource[], IEnumerable<TResult>> func, bool isFilterNull = true) { return DelegateToJson(source, enumerable => func(enumerable).ToJson(), isFilterNull); } /// <summary> /// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 /// </summary> /// <typeparam name="TSource"></typeparam> /// <param name="source">需要转换为JSON格式字符串的对象</param> /// <param name="func">JSON处理方法委托,返回JSON格式的字符串</param> /// <param name="isFilterNull">是否过滤IEnumerable<TSource> source中的null对象,默认为true</param> /// <returns>标准的JSON格式的字符串</returns> private static string DelegateToJson<TSource>(IEnumerable<TSource> source, Func<TSource[], string> func, bool isFilterNull = true) { if (source == null) { return EmptyJson; } TSource[] enumerable; if (isFilterNull) { //过滤null enumerable = source.Where(t => t != null).ToArray(); } else { //不过滤null,但上层需要注意内里面有null对象时,可能会导致Where或Select引发异常。 enumerable = source as TSource[] ?? source.ToArray(); } return enumerable.Any() ? func(enumerable) : EmptyJson; } #endregion } }
用法案例:
class Program { static void Main(string[] args) { //ToJson 方法 Test #region 默认过滤null对象 var list1 = new List<Test> { new Test {Id = 10, Type = 21, Name="Allen"}, new Test {Id = 11, Type = 22}, new Test {Id = 12, Type = 23}, new Test {Id = 13, Type = 24, Name="Peter"}, null, new Test {Id = 13, Type = 24, Name=null} }; //指定json数据所需要的属性 string jsonString = list1.ToJson(t => new { id = t.Id, type = t.Type }); //推荐写法,连true都省略掉 //string jsonString = JsonHelper.ToJson(list1, t => new { id = t.Id, type = t.Type }); //不推荐该写法 //string jsonString = list1.ToJson(t => new { id = t.Id, type = t.Type }, true); Console.WriteLine(jsonString); //筛选出Name为"Allen"的对象 string jsonString2 = list1.ToJson(t => t.Name == "Allen"); //推荐写法,连true都省略掉 //string jsonString2 = JsonHelper.ToJson(list1, t => t.Name == "Allen"); //不推荐该写法 //string jsonString2 = list1.ToJson(t => t.Name == "Allen", true); Console.WriteLine(jsonString2); //筛选出Name为"Allen"的对象,并且指定json数据所需要的属性 string jsonString3 = list1.ToJson(t => t.Name == "Allen", t => new { id = t.Id, type = t.Type }); //推荐写法,连true都省略掉 //string jsonString3 = JsonHelper.ToJson(list1, t => t.Name == "Allen", t => new { id = t.Id, type = t.Type }); //不推荐该写法 //string jsonString3 = list1.ToJson(t => t.Name == "Allen", t => new { id = t.Id, type = t.Type }, true); Console.WriteLine(jsonString3); #endregion #region 不过滤null对象 var list2 = new List<Test> { new Test {Id = 10, Type = 21, Name="Allen"}, new Test {Id = 11, Type = 22, Name="Bolong"}, new Test {Id = 12, Type = 23, Name="Popo"}, new Test {Id = 13, Type = 24, Name="Peter"}, new Test {Id = 16, Type = 25, Name="Willy"} }; //指定json数据所需要的属性 string jsonString4 = list2.ToJson(t => new { id = t.Id, type = t.Type }, false); Console.WriteLine(jsonString4); //筛选出Name为"Allen"的对象 string jsonString5 = list2.ToJson(t => t.Name == "Allen", false); Console.WriteLine(jsonString5); //筛选出Name为"Allen"的对象,并且指定json数据所需要的属性 string jsonString6 = list2.ToJson(t => t.Name == "Allen", t => new { id = t.Id, type = t.Type }, false); Console.WriteLine(jsonString6); #endregion //FromJson<T> 方法 Test List<Test> testList1 = jsonString.FromJson<List<Test>>(); List<Test> testList2 = jsonString2.FromJson<List<Test>>(); Test test = jsonString3.FromJson<Test>(); //弱类型 Test var test2 = jsonString.FromJson(); Newtonsoft.Json.Linq.JArray test3 = test2; Console.ReadKey(); } } internal class Test { public int Type { get; set; } public int Id { get; set; } public string Name { get; set; } }
PS:有更好的封装建议吗?
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。