3

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.

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Mashtani
  • 621
  • 11
  • 24
  • Slightly different question, but I suspect the second part of the accepted answer will help you. [prevent property from being serialized in web api](http://stackoverflow.com/questions/11851207/prevent-property-from-being-serialized-in-web-api) – CollinD Jan 02 '16 at 09:44
  • The question you mentioned does not have any accepted answer. @CollinD – Hamid Pourjam Jan 02 '16 at 11:39
  • @dotctor Accepted answers are irrelevant for duplicates. For all you know the OP of the original question never bothered to return or accept. – Mark Rotteveel Jan 02 '16 at 11:42
  • 1
    @CollinD that one isn't a duplicate, because it is an *unconditional* ignore; conditional ignore has pretty much completely different mechanisms – Marc Gravell Jan 02 '16 at 11:43

1 Answers1

9

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

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • 4
    For context of readers: this is a well-established pattern, respected by `PropertyDescriptor` (which means: `PropertyGrid` etc), `XmlSerializer`, and a wide range of other serializers, including Json.NET, protobuf-net, etc – Marc Gravell Jan 02 '16 at 11:45
  • Thank you @dotctor, it was helpful. – Mashtani Jan 02 '16 at 12:11