Remove null properties of an object sent to Json MVC

前端 未结 3 718
花落未央
花落未央 2020-12-17 18:51
namespace Booking.Areas.Golfy.Models
{
    public class Time
    {
        public string   time            { get; set; }
            


        
3条回答
  •  不思量自难忘°
    2020-12-17 19:32

    You can't use the default Json ActionResult to remove null properties.

    You can take a look at JSON.NET, it has an attribute that you can set to remove the property if it is null

    [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
    

    Or if you don't want to use other libraries you can create your own json custom ActionResult and register a new converter for the default JavaScriptSerializer, like this:

    public class JsonWithoutNullPropertiesResult : ActionResult
    {
        private object Data { get; set; }
    
        public JsonWithoutNullPropertiesResult(object data)
        {
            Data = data;
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = "application/x-javascript";
            response.ContentEncoding = Encoding.UTF8;
    
            if (Data != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                serializer.RegisterConverters(new[] { new NullPropertiesConverter() });
                string ser = serializer.Serialize(Data);
                response.Write(ser);
            }
        }
    }
    
    public class NullPropertiesConverter : JavaScriptConverter
    {
        public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
        {
            var toSerialize = new Dictionary();
    
            foreach (var prop in obj.GetType()
                                    .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                    .Select(p => new
                                    {
                                        Name = p.Name,
                                        Value = p.GetValue(obj)
                                    })
                                    .Where(p => p.Value != null))
            {
                toSerialize.Add(prop.Name, prop.Value);
            }
    
            return toSerialize;
        }
    
        public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }
    
        public override IEnumerable SupportedTypes
        {
            get { return GetType().Assembly.GetTypes(); }
        }
    }
    

    And now in your view:

    public ActionResult Index()
    {
        Teetimes r = BookingManager.GetBookings();
        return new JsonWithoutNullPropertiesResult(t);
    }
    

提交回复
热议问题