0

I have a ASP.NET WebAPI application that sends to the Javascript client json responses.

I have a class that I use to build a tree view:

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; }
}

I have to hide on my Json response the children property when that element doesn't have any children and also hide the cls and expanded property.

I should get something like this:

[{
    "text": "To Do", 
    "cls": "folder",
    "expanded": true,
    "children": [{
        "text": "Go jogging",
        "leaf": true,
        "checked": true
    },{
        "text": "Take a nap",
        "leaf": true,
        "checked": false
    },{
        "text": "Climb Everest",
        "leaf": true,
        "checked": false
    }]
},

Any clue?

1 Answer 1

2

There is a concept called Conditional Serialization in Json.NET. Take a look here for the documentation.

In your case, you could do something like:

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.