c# - 有条件地忽略属性序列化

标签 c# asp.net .net asp.net-web-api json.net

我有一个 Asp.Net WebApi 项目,我想返回 Json 格式的产品列表和一个特定产品。

这是我的产品模型:

public class Product
{
   public int Id { get; set; }
   public string ShortString { get; set; }
   public string LongString { get; set; } 
}

这是我的 ApiController:

public class ProductController : ApiController
{

     public IQueryable<Product> Get()
     {
        return Context.Products;
     }

     public IHttpActionResult Get(int id)
     {
        var p = Context.Products.FirstOrDefault(m => m.Id == id);

        if (p == null)
            return NotFound();

        return Ok(p);
     }
 }

我想返回一个特定产品中的 LongString 字段,但不返回产品列表中的字段。 Json.Net 库中是否有条件 [JsonIgnore] 属性。

最佳答案

您必须定义一个名为 ShouldSerialize{PropertyName} 的公共(public)方法,它会在您的类中返回 bool。

public class Product
{
    public int Id { get; set; }
    public string ShortString { get; set; }
    public string LongString { get; set; }

    public bool ShouldSerializeLongString()
    {
        return (Id < 2); //maybe a more meaningful logic
    }
}

测试它

var l = new List<Product>()
{
    new Product() {Id = 1, ShortString = "s", LongString = "l"},
    new Product() {Id = 2, ShortString = "s", LongString = "l"}
};

Console.WriteLine(JsonConvert.SerializeObject(l));

结果是

[{"Id":1,"ShortString":"s","LongString":"l"},{"Id":2,"ShortString":"s"}]

关于c# - 有条件地忽略属性序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34564521/

相关文章:

c# - 更改带有选项卡的接受按钮

c# - Blazor 全屏

c# - 如何从保存文件对话框中获取文件扩展名?

c# - 自定义登录 ASP.NET C#

.net - .NET 编译器(例如 csc.exe、vbc.exe)是否使用 Reflection.Emit()?

.net - .NET 2 或 .NET 4 中的 msxsl 内存泄漏错误是否已修复?

c# - Unity 中出现此错误 "Download over http ,please consider updating to https"的任何永久解决方案?

javascript - Chrome 有时不请求 CSS 页面

asp.net - ASP.NET Webforms 中的 ViewState 替代方案

c# - 如何在asp.net下异步运行持久进程?