我有一个 Asp.Net WebApi 项目,我想返回 Json 格式的产品列表和一个特定产品。
这是我的产品模型:
public class Product
{
public int Id { get; set; }
public string ShortString { get; set; }
public string LongString { get; set; }
}
这是我的 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]
属性。
最佳答案
您必须定义一个名为 ShouldSerialize{PropertyName}
的公共(public)方法,它会在您的类中返回 bool。
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"}]
关于c# - 有条件地忽略属性序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34564521/