asp net core return json with empty property (not null)

Viewed 262

What ways are there for the controller to return json with empty property model or list, but not null

Example model:

 public class Model
        {
            public string name;
            public string comment;
            public List<Contact> Contacts;
        }
        public  class Contact
        {
            public int id;
            public string title;
        }
        static void Main(string[] args)
        {
            Model model1 = new Model() 
            { 
                name = "Max"
            };
        }

and if we have an empty list, then I want to get such a json:

{
   "name": "Max",
   "comment": "",
   "contacts": []
}
2 Answers

You can use private fields

public class Model
{
    private string _name = "";
    private string _comment = "";
    private List<Contact> _contacts = new List<Contact>();

    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            if (_name != value) _name = value;
        }
    }

    public string Comment
    {
        get
        {
            return _comment;
        }
        set
        {
            if (_comment != value) _comment = value;
        }
    }

    public List<Contact> Contacts
    {
        get
        {
            return _contacts;
        }
        set
        {
            if (value != null && value.Length > 0) _contacts = value;
        }
    }
}

Initializing Contacts will send empty set when your Serialize

public class Model
{
    public string name;
    public string comment;
    public List<Contact> Contacts = new List<Contact>();
}
Related