[英]How can i return null for a json property instead of “data”: []
我已經將我的財產裝飾為
[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
})
}
NullValueHandling
屬性處理null。 LINQ的select
從不返回null,而是返回一個空IEnumerable
。 這就是為什么您在結果JSON中看到“data”: []
的原因。
若要使NullValueHandling
屬性起作用,當結果為空IEnumerable
時,返回null。 例如,您可以根據您的情況調整以下代碼。
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
})
}
考慮將查詢分解為較小的塊。
經過數小時的拔發,成功。
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的啟發
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.