1

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 2

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.