Newtonsoft.Json动态过滤属性

接口写的多了,会发现很多的问题。同一个dto,不同的action返回的字段个数不一样。往往开发人员因为懒或者各种原因一股脑的全返回,会浪费很多流量且用户体验很差。

当然也会有负责一些的,根据不同的action定义不同的output类。毫无疑问这很麻烦,浪费开发时间。博主本人也是深受其扰,之前看到一篇博文 Newtonsoft.Json高级用法 里面有说到动态决定是属性是否序列化。深得我心于是上手试了一下。博文里的代码很不完善

本人的项目返回类型均为 OutputModel(Status、Message、Data(数据))。把output丢给json序列化的时候,拿到的只有属性只有Status、Message、Data。而我们要针对的是Data类型的属性。本人进行改造后。由于过滤的属性清单与OutPutModel的又不一致(因为我们要序列化的是output,我们传入的是data里的属性),无法进行序列化,后面又实验了一下效率如何。如下图,5w次循环竟然与之前差了71倍之多。于是博主准备自己动手去写一个


自己动手

动手之前应该思考一下,我们需要的是什么效果。

  • 根据传入数组动态决定哪些属性需要初始化
  • 针对OutPutModel的处理
  • 效率的高效,至少要直接序列化的差距不会太大

我想要用法是在序列化的时候传入一个字符串数组(也就是需要序列化属性),这里对思路进行梳理一下

return Json(output,new []{"Name","Age"})
  • 使用反射,拿到output.Data的Type
  • 使用type创建一个实例,循环type的GetProperties。判断property是否在传入的字符串数组中
  • 使用property.GetValue获取到属性值,然后再SetValue到创建的实例中
  • 把实例赋值给output.Data

很简单,就是对output的data进行一次替换,下面代码很完美的可以解决问题。

private static void Filtered(OutputModel output, string[] param)
{
Type type = null;
if (param == null || param.Length <= 0)
{
return;
}
type = null; if (output.Data == null) return;
type = output.Data.GetType();
object result = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
if (!((IList)param).Contains(property.Name)) continue;
object value = property.GetValue(output.Data, null);
property.SetValue(result, value);
}
output.Data = result;
}

细心的同学可能会发现上面的少了针对List的处理

      Type type = null;
if (output.Data is IList)
{
var dataList = output.Data as IList;
if (dataList.Count > 0)
{
type = dataList[0].GetType();
var result = Activator.CreateInstance(output.Data.GetType()) as IList; foreach (var temp in dataList)
{
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
if (!((IList) param).Contains(property.Name)) continue;
object value = property.GetValue(temp, null);
property.SetValue(instance, value);
}
result.Add(instance);
}
output.Data = result;
}
}

上面的一些代码运行起来效率比原生5000次只低不50-100ms,完全可以接受。但是会发现序列化后我们不想要被序列化的属性值变成了null。研究了一下问题出在

var instance = Activator.CreateInstance(type);  这里,因为我们创建的还是那个类嘛。。属性也无法被砍掉。想了想这里可以用动态类型去实现。

                type = obj.GetType();
var result = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in type.GetProperties())
{
if (retain)
{
if (!((IList)props).Contains(property.Name.ToLower())) continue;
}
else
{
if (((IList)props).Contains(property.Name.ToLower())) continue;
}
object value = property.GetValue(obj, null);
result.Add(property.Name, value); }
obj = result;

实验了一下对效果非常满意,另外一个有意思的事情是效率竟然比原生要快上一倍

这张图直接进行序列化

这张图是用过滤了属性

下面除上完整的代码,有需要的同学可以进行使用

using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using Tool.Response; namespace MvcCustommade
{
public class LimitPropsContractResolver
{ private static object Filtered(object obj, string[] props, bool retain)
{ if (obj == null)
return null;
Type type = null;
if (obj is IList)
{
var dataList = obj as IList;
if (dataList.Count > 0)
{
type = dataList[0].GetType();
List<IDictionary<string, object>> result = new List<IDictionary<string, object>>(); foreach (var temp in dataList)
{
var instance = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in type.GetProperties())
{
if (retain)
{
if (!((IList)props).Contains(property.Name.ToLower())) continue;
}
else
{
if (((IList)props).Contains(property.Name)) continue;
} object value = property.GetValue(temp, null);
instance.Add(property.Name, value);
}
result.Add(instance);
}
obj = result;
}
}
else
{ type = obj.GetType();
var result = new ExpandoObject() as IDictionary<string, Object>;
foreach (var property in type.GetProperties())
{
if (retain)
{
if (!((IList)props).Contains(property.Name.ToLower())) continue;
}
else
{
if (((IList)props).Contains(property.Name.ToLower())) continue;
}
object value = property.GetValue(obj, null);
result.Add(property.Name, value); }
obj = result;
} return obj;
} /// <summary>
/// 过滤无用的属性
/// </summary>
/// <param name="output">返回的数据</param>
/// <param name="props">过滤的属性数组</param>
/// <param name="retain">过滤的数组是包含还是不包含</param>
public static object CreateProperties(object output, string[] props, bool retain)
{
if (props == null || props.Length <= 0)
{
return output;
}
if (output == null)
{
return null;
}
for (int i = 0; i < props.Length; i++)
{
props[i] = props[i].ToLower();
}
if (output is OutputModel)
{
var outputModel = output as OutputModel;
if (outputModel.Data == null)
{
return outputModel;
}
outputModel.Data = Filtered(outputModel.Data, props, retain);
return outputModel; #region 初始版 //Type type = null; //if (outputModle.Data is IList)
//{
// var ss = outputModle.Data as IList;
// if (ss.Count > 0)
// {
// type = ss[0].GetType();
// List<IDictionary<string, object>> result = new List<IDictionary<string, object>>(); // foreach (var temp in ss)
// {
// var instance = new ExpandoObject() as IDictionary<string, Object>;
// foreach (var property in type.GetProperties())
// {
// if (retain)
// {
// if (!((IList)props).Contains(property.Name)) continue;
// }
// else
// {
// if (((IList)props).Contains(property.Name)) continue;
// } // object value = property.GetValue(temp, null);
// instance.Add(property.Name, value);
// }
// result.Add(instance);
// }
// outputModle.Data = result;
// }
//}
//else
//{
// if (outputModle.Data == null) return;
// type = outputModle.Data.GetType();
// var result = new ExpandoObject() as IDictionary<string, Object>;
// foreach (var property in type.GetProperties())
// {
// if (retain)
// {
// if (!((IList)props).Contains(property.Name)) continue;
// }
// else
// {
// if (((IList)props).Contains(property.Name)) continue;
// }
// object value = property.GetValue(outputModle.Data, null);
// result.Add(property.Name, value); // }
// outputModle.Data = result;
//} #endregion
}
else
{
output = Filtered(output, props, retain);
return output;
} }
}
}

Newtonsoft.Json动态过滤属性的更多相关文章

  1. Newtonsoft.Json高级用法 1.忽略某些属性 2.默认值的处理 3.空值的处理 4.支持非公共成员 5.日期处理 6.自定义序列化的字段名称

    手机端应用讲究速度快,体验好.刚好手头上的一个项目服务端接口有性能问题,需要进行优化.在接口多次修改中,实体添加了很多字段用于中间计算或者存储,然后最终用Newtonsoft.Json进行序列化返回数 ...

  2. EF 实体+ Newtonsoft.Json 输出JSON 时动态忽略属性的解决方法

    最近的项目采用的是 ASP.NET mvc 4.0 + entity framework 5.0 ,后台以JSON形式抛出数据是借助于Newtonsoft.Json ,   要想忽略的属性前面添加特性 ...

  3. Newtonsoft.Json输出JSON 时动态忽略属性

    一,前言 最近做项目采用Json形式和其他客户端交互,借助于Newtonsoft.Json . 由于业务场景不同,输出的Json内容也不同.要想忽略的属性,可以借助Newtonsoft.Json的特性 ...

  4. Newtonsoft.Json输出Json时动态忽略属性

    一,前言 最近做项目采用Json形式和其他客户端交互,借助于Newtonsoft.Json . 由于业务场景不同,输出的Json内容也不同.要想忽略的属性,可以借助Newtonsoft.Json的特性 ...

  5. c#使用 Newtonsoft.Json 将entity转json时,忽略为null的属性

    c#使用 Newtonsoft.Json 将entity转json时,忽略为null的属性,直接在属性上加下面的特性 [JsonProperty(NullValueHandling=NullValue ...

  6. C# Newtonsoft.Json JObject移除属性,在序列化时忽略

    原文 C# Newtonsoft.Json JObject移除属性,在序列化时忽略 一.针对 单个 对象移除属性,序列化时忽略处理 JObject实例的 Remove() 方法,可以在 指定序列化时移 ...

  7. Newtonsoft.Json 指定某个属性使用特定的时间格式

    Newtonsoft.Json 指定某个属性使用特定的时间格式 Intro Newtonsoft.Json 是 .NET 下最受欢迎 JSON 操作库,原为 JSON.Net 后改名为 Newtons ...

  8. Newtonsoft.Json.Linq.JObject 遍历验证每个属性内容

    业务需求,拦截器验证每个请求inputstream(实际是application/json流)的数据,但是json反序列化实体格式不同. var req = filterContext.Request ...

  9. 【Newtonsoft.Json】json序列化小驼峰格式(属性名首字母小写)

    我是一名 ASP.NET 程序员,专注于 B/S 项目开发.累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html 只需要设置JsonSe ...

随机推荐

  1. weblogic.nodemanager.common.ConfigException: Native version is enabled but nodemanager native library could not be loaded 解决办法

    近日在一个原本工作正常的weblogic web server(操作系统为redhat 64位系统)上折腾安装redis/hadoop等东东,yum install了一堆第3方类库后,重启weblog ...

  2. java调用.net asmx / wcf

    一.先用asmx与wcf写二个.net web service: 1.1 asmx web服务:asmx-service.asmx.cs using System; using System.Coll ...

  3. python数字图像处理(18):高级形态学处理

    形态学处理,除了最基本的膨胀.腐蚀.开/闭运算.黑/白帽处理外,还有一些更高级的运用,如凸包,连通区域标记,删除小块区域等. 1.凸包 凸包是指一个凸多边形,这个凸多边形将图片中所有的白色像素点都包含 ...

  4. 翻译qmake文档(一) qmake指南和概述

    翻译qmake文档 目录 英文文档连接: http://qt-project.org/doc/qt-5/qmake-manual.html http://qt-project.org/doc/qt-5 ...

  5. 反射 实现不同模型相同属性赋值 第二集(automapper)

    前言: 两年前写过一个 反射实现不同模型相同属性赋值 只能简单的实现两个model 相同属性名,相同类型赋值 最近又遇到这个问题,需要对相同属性名或者指定属性名 不同类型(复杂对象,如:List< ...

  6. 在eclipse中使用第三方库总结

    一.建立user library 导入第三方jar文件,最简单的方式是:右键工程/属性/java build path/add external jars. 另一种方式是:window/prefren ...

  7. python基础-编码_if条件判断

    一.第一句Python代码 在 /home/dev/ 目录下创建 hello.py 文件,内容如下: [root@python-3 scripts]# cat hello.py #!/usr/bin/ ...

  8. Bete冲刺第七阶段

    Bete冲刺第七阶段 今日工作: web: 新增通知处理接口 ios: 重写登录逻辑,添加创建行程填写.注册 POP界面 目前所遇问题: web: web目前进展顺利,暂时还没有遇到编码的问题. iO ...

  9. mysql常用方法学习

    环境 create table phople ( id int(11) not null primary key auto_increment, name char(20) not null, sex ...

  10. Eclipse导入 appcompat,design兼容包

    从Android studio推出1.0正式版后,就一直在as上开发项目,但是最近要测试一个项目,是eclipse结构,导入as后,是各种报错信息,决定改成eclipse. 其中项目中用到了ppcom ...