简体   繁体   English

在WebAPI中实现JSON ShouldSerialize

[英]Implementing JSON ShouldSerialize in WebAPI

I have a C# POCO that looks like the following 我有一个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; }
}

I need to be able to hide and show UserId and Login properties based on certain condition and return them as JSON in WebAPI. 我需要能够根据特定条件隐藏和显示UserId和Login属性,并在WebAPI中将它们作为JSON返回。 However, somehow the WebAPI JsonSerializer does not honor ShouldSerialize property. 但是,以某种方式,WebAPI JsonSerializer不支持ShouldSerialize属性。 How to make this code below to work ? 如何使下面的代码正常工作? I am using ASP.NET 5. 我正在使用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);
    }
}

My guess is that you need to use ShouldSerialize** method , not the property. 我的猜测是您需要使用ShouldSerialize** 方法 ,而不是属性。

Something like: 就像是:

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

Hope it will help. 希望它会有所帮助。

ASP.NET Web API uses reflection to call ShouldSerialize* methods to determine (not property) if specific public properties should be serialized. ASP.NET Web API使用反射来调用ShouldSerialize *方法来确定(而非属性)是否应序列化特定的公共属性。

For example, 例如,

private bool _shouldSerializeUserId;
// You can this method to set value.
public void SetShouldSerializeUserId(bool shouldSerializeUserId)
{
   _shouldSerializeUserId = shouldSerialize;
}
public bool ShouldSerializeUserId()
{
   return _shouldSerializeUserId;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM