2016-05-04 22 views
0

我有一個C#POCO,看起來像下面實施JSON ShouldSerialize中的WebAPI

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

我需要能夠隱藏和顯示用戶名和登錄屬性,根據一定的條件和的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

您標記您的問題[標籤:asp.net的Web-API],但你的代碼似乎是從[標籤:asp.net-MVC。你爲什麼尋求答案?他們使用不同的JSON序列化器。 – dbc

+0

@dbc,我特意尋找web-api的答案,但是在ASP.NET 5中,web-api和mvc的區別都結合在一起。 –

回答

2

我的猜測是,你需要使用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; } 
} 

希望這將有助於。

+0

是的,方法的作品!謝謝。 –

1

的ASP.NET Web API使用反射來調用ShouldSerialize *方法確定(不屬性)如果具體的公共屬性應該被序列化。

例如,

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