博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JSON扩展类——JsonHelper
阅读量:7044 次
发布时间:2019-06-28

本文共 12007 字,大约阅读时间需要 40 分钟。

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        ///         /// 应用Formatting.None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串        ///         /// 任意一个对象        /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置        /// 
标准的JSON格式的字符串
public static string ToJson(object obj, JsonSerializerSettings jsonSettings) { return ToJson(obj, Formatting.None, jsonSettings); } /// /// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 /// /// 任意一个对象 /// 指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 ///
标准的JSON格式的字符串
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; } } /// /// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。
///
转换失败,或发生其它异常,则返回dynamic对象的默认值
///
/// 需要反序列化的JSON字符串 /// 在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 ///
dynamic对象
public static dynamic FromJson(this string json, JsonSerializerSettings jsonSettings) { return FromJson
(json, Formatting.None, jsonSettings); } ///
/// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据为dynamic对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。
///
转换失败,或发生其它异常,则返回dynamic对象的默认值
///
///
需要反序列化的JSON字符串 ///
指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 ///
在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 ///
dynamic对象
public static dynamic FromJson(this string json, Formatting format, JsonSerializerSettings jsonSettings) { return FromJson
(json, format, jsonSettings); } ///
/// 应用Formatting.None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。
///
转换失败,或发生其它异常,则返回T对象的默认值
///
///
需要反序列化的JSON字符串 ///
在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 ///
反序列化对象的类型
///
public static T FromJson
(string json, JsonSerializerSettings jsonSettings) where T : class, new() { return FromJson
(json, Formatting.None, jsonSettings); } ///
/// 应用指定的Formatting枚举值None和指定的JsonSerializerSettings设置,反序列化JSON数据到指定的.NET类型对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。
///
转换失败,或发生其它异常,则返回T对象的默认值
///
///
需要反序列化的JSON字符串 ///
指定 Newtonsoft.Json.JsonTextWriter 的格式设置选项 ///
在一个 Newtonsoft.Json.JsonSerializer 对象上指定设置,如果为null,则使用默认设置 ///
反序列化对象的类型
///
public static T FromJson
(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
(json, jsonSettings); } catch (JsonSerializationException) //在发生该异常后,再以集合的方式重试一次. { //LOG try { var array = JsonConvert.DeserializeObject
>(json, jsonSettings); result = array.FirstOrDefault(); } catch (Exception) { //LOG result = default(T); } } catch (Exception) { //LOG result = default(T); } return result; } #endregion #region Public Extend Methods ///
/// 反序列化JSON数据为dynamic对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个dynamic对象。
///
转换失败,或发生其它异常,则返回dynamic对象的默认值
///
///
需要反序列化的JSON字符串 ///
dynamic对象
public static dynamic FromJson(this string json) { return FromJson
(json, Formatting.None, JsonSettings); } ///
/// 反序列化JSON数据到指定的.NET类型对象 ///
如果发生JsonSerializationException异常,再以集合的方式重试一次,取出集合的第一个T对象。
///
转换失败,或发生其它异常,则返回T对象的默认值
///
///
需要反序列化的JSON字符串 ///
反序列化对象的类型
///
public static T FromJson
(this string json) where T : class, new() { return FromJson
(json, Formatting.None, JsonSettings); } ///
/// 应用默认的Formatting枚举值None和默认的JsonSerializerSettings设置,序列化对象到JSON格式的字符串 /// ///
任意一个对象 ///
标准的JSON格式的字符串
public static string ToJson(this object obj) { return ToJson(obj, Formatting.None, JsonSettings); } public static string ToJson
(this IEnumerable
source, Func
predicate, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
predicate, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(t => t != null).Select(selector), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
predicate, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
predicate, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
predicate, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } public static string ToJson
(this IEnumerable
source, Func
predicate, Func
selector, bool isFilterNull = true) { return DelegateToJson(source, enumerable => enumerable.Where(predicate).Select(selector), isFilterNull); } #endregion #region Private Methods ///
/// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 /// ///
///
///
需要转换为JSON格式字符串的对象 ///
集合/数组条件筛选方法委托,返回筛选后的集合/数组 ///
是否过滤IEnumerable
source中的null对象,默认为true ///
标准的JSON格式的字符串
private static string DelegateToJson
(IEnumerable
source, Func
> func, bool isFilterNull = true) { return DelegateToJson(source, enumerable => func(enumerable).ToJson(), isFilterNull); } ///
/// 委托处理需要序列化为JSON格式的对象,返回标准的JSON格式的字符串。 /// 默认过滤null对象,如果需要在上层调用时,自己进行条件过滤null对象, /// 则设置isFilterNull为false,不建议isFilterNull设置为false。 /// ///
///
需要转换为JSON格式字符串的对象 ///
JSON处理方法委托,返回JSON格式的字符串 ///
是否过滤IEnumerable
source中的null对象,默认为true ///
标准的JSON格式的字符串
private static string DelegateToJson
(IEnumerable
source, Func
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
{ 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
{ 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
方法 Test List
testList1 = jsonString.FromJson
>(); List
testList2 = jsonString2.FromJson
>(); Test test = jsonString3.FromJson
(); //弱类型 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:有更好的封装建议吗?

转载地址:http://itqal.baihongyu.com/

你可能感兴趣的文章
20个人事主管最常问的问题和最喜欢的答案
查看>>
说说API的防重放机制
查看>>
基于ThreadPool的简单工作管理器
查看>>
webservice 获取调用者IP
查看>>
Eclipse for php + Xdebug搭建PHP的调试环境
查看>>
非官方python库地址
查看>>
VBA 选择文件
查看>>
ADO.NET
查看>>
bzoj 2428: [HAOI2006]均分数据
查看>>
ART的堆内存布局
查看>>
MySQL创建数据库/表等基本命令操作
查看>>
CF每日一练(1.20)
查看>>
A damn at han’s Windows phone book 笔记(9 & 10)
查看>>
读书笔记 effective c++ Item 28 不要返回指向对象内部数据(internals)的句柄(handles)...
查看>>
当前日期往前推N天,当前日期往后推N天
查看>>
java正则匹配 指定内容以外的 内容
查看>>
linux网络编程
查看>>
自己实现简单的AOP(一)简介
查看>>
java.util.Map源码分析
查看>>
2018/11/29 算法时空(2) 算法导论第三章 函数的增长
查看>>