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. Fragment生命周期

  2. Java调用C/C++编写的第三方dll动态链接库(zz)

    这里主要用的方法是JNI.在网上查资料时看到很多人说用JNI非常的复杂,不仅要看很多的文档,而且要非常熟悉C/C++编程.恐怕有很多人在看到诸如此类的评论时已经决定绕道用其他方法了.本文将做详细的介绍 ...

  3. 整合Apache与PHP教程

    Apache下载安装完成后,PHP下载解压后,最重要的是如何将他们连接起来,就是整合到一起,让它们之间有联系,笔者根据自己多次配的经验和帮学弟学妹配时他们的理解程度整理了一个比较详细易理解的版本,下面 ...

  4. stack overflow错误分析

    stack overflow(堆栈溢出)就是不顾堆栈中分配的局部数据块大小,向该数据块写入了过多的数据,导致数据越界,结果覆盖了老的堆栈数据. 或者解释为 在长字符串中嵌入一段代码,并将过程的返回地址 ...

  5. centos7 安装nginx和php5.6.25遇到 无法访问php页面 报错file not found 问题解决

    php-fpm安装完成,nginx安装完成 netstap -ntl| 发下端口正常开启 iptables -L 返现9000端口已经开放 ps -aux|grep nginx 发下nginx进程正常 ...

  6. android之视频播放

    视频播放和音频播放一样,都是使用MediaPlayer来播放的,区别就是MediaPlayer播放视频时是直接在Activity中实现的,而音频播放则需要写到服务中去.使用MediaPlayer只支持 ...

  7. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  8. Oracle空串与null的处理

    来源于:http://blog.itpub.net/24870090/viewspace-1057853/ Oracle空串与null的处理[@more@] Oracle中的空字符串基本上是被当成空N ...

  9. Android Studio 优秀插件汇总

    第一部分 插件的介绍 Google 在2013年5月的I/O开发者大会推出了基于IntelliJ IDEA java ide上的Android Studio.AndroidStudio是一个功能齐全的 ...

  10. ubuntu14.04切换root用户

    打开命令窗口(CTRL+ALT+T),输入:sudo -s -->接着输入管理密码, -->已经切换到root用户