【问题标题】:asp net core return json with empty property (not null)asp net core 返回具有空属性的json(非空)
【发布时间】:2021-09-15 08:29:42
【问题描述】:

控制器有什么方法可以返回空属性的json 模型或列表,但不为空

示例模型:

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

如果我们有一个空列表,那么我想得到这样一个json:

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

【问题讨论】:

    标签: c# json asp.net-core


    【解决方案1】:

    您可以使用私有字段

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

    【讨论】:

      【解决方案2】:

      当您的序列化时,初始化联系人将发送空集

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

      【讨论】:

        猜你喜欢
        • 2011-10-15
        • 2021-10-15
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多