【问题标题】:How can i return null for a json property instead of "data": []如何为 json 属性返回 null 而不是“数据”:[]
【发布时间】:2017-02-27 00:05:28
【问题描述】:

我已将我的财产装饰为

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<Season> seasons { get; set; }

如果不存在记录,以下代码会出现问题,该代码返回 "seasons": []

from ul in userLeagues
select new Map.League
{
    id = ul.LeagueID,
    seasons = from ss in ul.Standings
              where inc.Seasons && ss.LeagueID == ul.LeagueID
              select new Map.Season
              {
                   seasonId = ss.Season.SeasonId,
                   seasonName = ss.Season.SeasonName
              })
}

【问题讨论】:

  • 我是 curios.. 为什么 LINQ 代码会有问题.. 它会返回包含数据的列表或空列表,并且 JSON 序列化程序会将其序列化... 只要解析 JSON 对象的应用程序抱怨它。
  • 发生这种情况是因为 linq 查询永远不会返回 null。这将返回一个 IQueryable,但是当它评估查询时,它将返回一个空列表,而不是 null。
  • LINQ 不会返回 null,因此您的 null 处理属性什么也不做。
  • 您执行 Queryable.ToList() 并检查计数并将目标变量设置为 null 如果计数为零
  • 考虑更改/简化您的问题查询,以便尝试回答的人可以在dotnetfiddle.net 中运行它。

标签: c# json entity-framework linq


【解决方案1】:

这是一个一般性的答案

NullValueHandling 属性处理 null。 LINQ 的 select 从不返回 null,而是返回一个空的 IEnumerable。这就是您在生成的 JSON 中看到 “data”: [] 的原因。

要使NullValueHandling 属性起作用,当结果为空IEnumerable 时返回null。例如,您可以根据您的情况调整以下代码。

Run in DotNetFiddle.

var foo = new List<string>();

var bar = !foo.Any()
    ? null
    : from f in foo select f;

Console.WriteLine(bar == null); // true

这可能是你的样子

from ul in userLeagues
let standings = from ss in ul.Standings
                where inc.Seasons && ss.LeagueID == ul.LeagueID
select new Map.League
{
    id = ul.LeagueID,
    seasons = !standings.Any()
        ? null
        : from ss in standings
          select new Map.Season
          {
              seasonId = ss.Season.SeasonId,
              seasonName = ss.Season.SeasonName
          })
}

一边

考虑将您的查询分解成更小的块。

【讨论】:

    【解决方案2】:

    经过数小时的拔毛,成功。

    private IEnumerable<Season> _seasons;
    
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public IEnumerable<Season> seasons
    {
        get { return _seasons == null || _seasons.Count() == 0 ? null : _seasons; }
        set { _seasons = value; }
    }
    

    特别感谢@ShaunLuttin 的启发

    【讨论】:

    • 这是一个非常干净的解决方案,好主意!您可以使用_seasons?.Count() == 0 而不是_seasons == null。此外,您应该使用_seasons.Any() 而不是使用Count() 枚举季节
    • @Mafii 改为获取 { return _seasons != null && _seasons .Any() ? _seasons:空;因为 .Any() 可能会抛出 NullException?
    • 您可以使用_seasons?.Any()。 .Any 只有在 seasons 不为空时才会执行。休息似乎不错,请不要忘记更新您的答案;)
    猜你喜欢
    • 2015-05-23
    • 1970-01-01
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多