Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally ignore property serialization

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.

like image 688
Mashtani Avatar asked Feb 15 '26 13:02

Mashtani


1 Answers

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

like image 118
Hamid Pourjam Avatar answered Feb 17 '26 03:02

Hamid Pourjam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!