C# 如果满足条件,则跳过序列化列表元素(Newtonsoft)

C# 如果满足条件,则跳过序列化列表元素(Newtonsoft),c#,asp.net,list,json.net,C#,Asp.net,List,Json.net,我正在使用Newtonsoft进行序列化,我想跳过对列表中特定元素的序列化 比如说,我有一门课: public class Car { public PropertyA A {get; set;} public PropertyB B {get; set;} public bool ShouldSerializeCar {get; set;} } 我有一个Action方法,它返回一个列表作为响应,如下所示: [HttpGet("cars", Name = "Ge

我正在使用Newtonsoft进行序列化,我想跳过对列表中特定元素的序列化

比如说,我有一门课:

public class Car
{
    public PropertyA A {get; set;}
    public PropertyB B {get; set;}
    public bool ShouldSerializeCar {get; set;}
}
我有一个Action方法,它返回一个
列表
作为响应,如下所示:

    [HttpGet("cars", Name = "GetCars")]
    [ProducesResponseType(typeof(IEnumerable<Car>), 200)]
    public async Task<IActionResult> GetCars()
    {
        var cars = new List<Car>();
        //Some code here that generates a list of Car//
        return cars;
    }
[HttpGet(“cars”,Name=“GetCars”)]
[产品响应类型(typeof(IEnumerable),200)]
公共异步任务GetCars()
{
var cars=新列表();
//这里的一些代码生成了一个汽车列表//
返回车辆;
}
当Newtonsoft序列化响应时,如果
ShouldSerializeCar
为false,是否可以跳过序列化列表项


请注意,我不能使用除Newtonsoft之外的其他库,因为它已在整个项目中使用

与其依赖Newtonsoft来完成这项工作,为什么不在序列化列表之前过滤列表

代码:

[HttpGet(“cars”,Name=“GetCars”)]
[产品响应类型(typeof(IEnumerable),200)]
公共异步任务GetCars()
{
var cars=_repo.GetCars(),其中(c=>c.shouldcar);
retur Ok(汽车);
}

为什么不在序列化列表之前过滤列表,而不依赖Newtonsoft来完成这项工作

代码:

[HttpGet(“cars”,Name=“GetCars”)]
[产品响应类型(typeof(IEnumerable),200)]
公共异步任务GetCars()
{
var cars=_repo.GetCars(),其中(c=>c.shouldcar);
retur Ok(汽车);
}

序列化程序用于序列化。。。它可能会跳过不需要的属性,而不是collectionSerializer中的元素用于序列化。。。它可能会从集合中跳过不需要的属性而不是元素
[HttpGet("cars", Name = "GetCars")]
[ProducesResponseType(typeof(IEnumerable<Car>), 200)]
public async Task<IActionResult> GetCars()
{
    var cars = _repo.GetCars().Where(c => c.ShouldSerializeCar );
    retur Ok(cars);
}