我有一个C#POCO,如下所示
public class Notice
{
public bool ShouldSerializeUserId { get;set; }
public int UserId { get; set; }
public bool ShouldSerializeLogin { get; set; }
public string Login { get; set; }
public string Message { get;set; }
}
我需要能够根据特定条件隐藏和显示UserId和Login属性,并在WebAPI中将它们作为JSON返回。但是,不知何故,WebAPI JsonSerializer不支持ShouldSerialize属性。如何使下面的代码工作?我正在使用ASP.NET 5.
using Microsoft.AspNet.Mvc;
public class MyController : Controller
{
public IActionResult Get()
{
List<Notice> notices = NoticeRepository.GetNotices();
//need to show or hide UserId or Login here...
return Json(notices);
}
}
答案 0 :(得分:3)
我的猜测是你需要使用ShouldSerialize**
method,而不是财产。
类似的东西:
public class Notice
{
public int UserId { get; set; }
public bool ShouldSerializeUserId ()
{
return // your condition;
}
public string Login { get; set; }
public bool ShouldSerializeLogin ()
{
return // your condition;
}
public string Message { get;set; }
}
希望它会有所帮助。
答案 1 :(得分:1)
ASP.NET Web API使用反射来调用 ShouldSerialize * methods 来确定 (不是属性) ,如果应该序列化特定的公共属性。
例如,
private bool _shouldSerializeUserId;
// You can this method to set value.
public void SetShouldSerializeUserId(bool shouldSerializeUserId)
{
_shouldSerializeUserId = shouldSerialize;
}
public bool ShouldSerializeUserId()
{
return _shouldSerializeUserId;
}