Magals
Magals

Reputation: 13

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

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": []
}

Upvotes: 1

Views: 554

Answers (2)

ORaf
ORaf

Reputation: 56

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

Upvotes: 1

Krishna Varma
Krishna Varma

Reputation: 4250

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

Upvotes: 0

Related Questions