C# 避免发送json属性

C# 避免发送json属性,c#,asp.net-mvc-4,asp.net-web-api,json.net,C#,Asp.net Mvc 4,Asp.net Web Api,Json.net,我有一个ASP.NETWebAPI应用程序,它向Javascript客户端发送json响应 我有一个用于构建树状视图的类: public class TreeViewModel { public string text { get; set; } public string cls { get; set; } public bool expanded { get; set; } [JsonProperty(PropertyName = "checked")]

我有一个ASP.NETWebAPI应用程序,它向Javascript客户端发送json响应

我有一个用于构建树状视图的类:

public class TreeViewModel
{
    public string text { get; set; }
    public string cls { get; set; }
    public bool expanded { get; set; }
    [JsonProperty(PropertyName = "checked")]
    public bool checked { get; set; }
    public bool leaf { get; set; }
    public List<TreeViewModel> children { get; set; }
}

有什么线索吗?

在Json.NET中有一个称为条件序列化的概念。查看文档

在您的情况下,您可以执行以下操作:

public class TreeViewModel
{
    public string Text { get; set; }
    public string Cls { get; set; }
    public bool Expanded { get; set; }
    [JsonProperty(PropertyName = "checked")]
    public bool Checked { get; set; }
    public bool Leaf { get; set; }
    public List<TreeViewModel> Children { get; set; }

    public bool ShouldSerializeCls()
    {
        return Children != null && Children.Count > 0;
    }

    public bool ShouldSerializeExpanded()
    {
        return Children != null && Children.Count > 0;
    }

    public bool ShouldSerializeChildren()
    {
        return Children != null && Children.Count > 0;
    }
}
公共类树视图模型
{
公共字符串文本{get;set;}
公共字符串Cls{get;set;}
公共布尔扩展{get;set;}
[JsonProperty(PropertyName=“checked”)]
公共布尔检查{get;set;}
公共布尔叶{get;set;}
公共列表子项{get;set;}
公共布尔值应为CLS()
{
返回子项!=null&&Children.Count>0;
}
公共布尔值应该扩展()
{
返回子项!=null&&Children.Count>0;
}
公共学校应该为孩子们
{
返回子项!=null&&Children.Count>0;
}
}
public class TreeViewModel
{
    public string Text { get; set; }
    public string Cls { get; set; }
    public bool Expanded { get; set; }
    [JsonProperty(PropertyName = "checked")]
    public bool Checked { get; set; }
    public bool Leaf { get; set; }
    public List<TreeViewModel> Children { get; set; }

    public bool ShouldSerializeCls()
    {
        return Children != null && Children.Count > 0;
    }

    public bool ShouldSerializeExpanded()
    {
        return Children != null && Children.Count > 0;
    }

    public bool ShouldSerializeChildren()
    {
        return Children != null && Children.Count > 0;
    }
}