问题
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