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> /// 反序列化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> /// 反序列化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數據到指定的.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>(); Console.ReadKey(); } } internal class Test { public int Type { get; set; } public int Id { get; set; } public string Name { get; set; } }
PS:有更好的封裝建議嗎?