项目中用的类似这样需求,根据给定的参数,返回对象中动态保留给定的属性。几经周折,将最终方法展示处理,开始的时候,接口返回值一直用具体对象,剔除完属性的Json,返回的时候再反序列化,有把剔除掉的属性给还原了,最后返回值使用了Object ,一切安好。SetNullWhenIgnore 方法最后 做了对{} {} {} 的处理。用的类似的,大家抄一下,免得花费大量时间搞这玩意(我大概花了大半天时间,挺费神的)
/// <summary>
/// Ignoring properties marked(FROM CBI)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classData"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static string SetNullWhenIgnore<T>(this T classData, string columnName)
{
if (classData != null)
{
var attrClumn = columnName.Split(',');
foreach (var prop in classData.GetType().GetRuntimeProperties())
{
var IsGenericType = prop.PropertyType.IsGenericType;
var IsList = prop.PropertyType.GetInterface("IEnumerable", false);
if (IsGenericType && IsList != null)
{
var listObject = prop.GetValue(classData) as IEnumerable<object>;
if (listObject == null) continue;
foreach (var obj in listObject)
{
SetNullWhenIgnore(obj, columnName);
}
}
else
{
//if (attrClumn.FirstOrDefault(prop.Name) == null) //ignore
if (!attrClumn.Contains(prop.Name))
{
prop.SetValue(classData, null); //Setting Property's value is null when it need to ignore
}
else
{
if (prop.GetValue(classData) == null) // can't ignore
{
prop.SetValue(classData, "");//Setting Property's value is '' when its value is null
}
}
}
}
}
var cleanJson = JsonConvert.SerializeObject(classData, new DefaultJsonSerializer()).Replace("{},", "").Replace("{}", "");
return cleanJson;
}
上面的处理方法,通过递归可以处理多层嵌套,返回Json 字符串,最后返回的时候 剔除字符串 中的{},{},{}
接口中调用:
public async Task<APIResult<System.Object>> PostReport(ReportRequestDto reportDto)
{
string columnsName = reportDto.ExportInfo[0].Columns; //需要保留的字段,用,号隔开
//var allData= 获取List属性集合
var jsonStr=allData.SetNullWhenIgnore(columnsName); // 开始调用(递归处理),剔除掉非保留字段
return APIResult.getSuccess(JsonConvert.DeserializeObject<System.Object>(jsonStr));
}