【问题标题】:Skip serializing a list element if a condition is satisfied (Newtonsoft) [duplicate]如果满足条件,则跳过序列化列表元素(Newtonsoft)[重复]
【发布时间】:2019-12-20 19:56:35
【问题描述】:

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

说,我有课:

public class Car
{
    public PropertyA A {get; set;}
    public PropertyB B {get; set;}
    public bool ShouldSerializeCar {get; set;}
}

我有一个 Action 方法,它返回一个 List<Car> 作为响应:

    [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;
    }

Newtonsoft 序列化响应时,是否可以跳过序列化 ShouldSerializeCar 为假的列表项?

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

【问题讨论】:

  • Serializer 用于序列化......它可能会跳过不需要的属性而不是集合中的元素

标签: c# asp.net list json.net


【解决方案1】:

与其依靠 Newtonsoft 来执行此操作,您为什么不在序列化列表之前过滤您的列表?

代码:

[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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 2017-04-07
    • 2013-11-15
    • 2015-11-03
    相关资源
    最近更新 更多