conditionally ignore property serialization

﹥>﹥吖頭↗ 提交于 2019-12-10 19:22:42

问题


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

This is my product model:

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

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

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.


回答1:


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

Testing it

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

result is

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



来源:https://stackoverflow.com/questions/34564521/conditionally-ignore-property-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!