有条件地忽略属性序列化 [英] conditionally ignore property serialization

查看:95
本文介绍了有条件地忽略属性序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Asp.Net WebApi project and I want to return a list of product in Json format and one specific product.

这是我的产品型号:

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

这是我的ApiController:

And this is my 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]属性.

I want to return LongString field in the one specific product but not in the list of products. Is there any conditional [JsonIgnore] attribute in Json.Net library.

推荐答案

您必须定义一个名称为ShouldSerialize{PropertyName}的公共方法,该方法将在类内部返回bool.

You must define a public method with the name ShouldSerialize{PropertyName} which returns bool inside your class.

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"}]

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

这篇关于有条件地忽略属性序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆