有条件地忽略属性序列化

Mas*_*ani 3 .net c# asp.net json.net asp.net-web-api

我有一个Asp.Net WebApi项目,我想返回Json格式的产品列表和一个特定的产品。

这是我的产品型号:

public class Product
{
   public int Id { get; set; }
   public string ShortString { get; set; }
   public string LongString { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

这是我的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);
     }
 }
Run Code Online (Sandbox Code Playgroud)

我想返回LongString一种特定产品中的字段,而不是产品列表中的字段。[JsonIgnore]Json.Net库中是否有任何条件属性。

Ham*_*jam 5

您必须定义一个公共方法,该方法的名称ShouldSerialize{PropertyName}将在类内部返回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
    }
}
Run Code Online (Sandbox Code Playgroud)

测试它

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));
Run Code Online (Sandbox Code Playgroud)

结果是

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

  • 对于读者而言:这是一个完善的模式,受到PropertyDescriptor(意味着:PropertyGrid等),XmlSerializer和许多其他序列化器(包括Json.NET,protobuf-net等)的尊重。 (3认同)