Remove null properties of an object sent to Json MVC

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


        
3条回答
  •  被撕碎了的回忆
    2020-12-17 19:43

    The answers given are interresting, but I had started using DataContractJsonSerializer in the meantime.
    And it does the job fine without the need of using a third party framework (though JSON.Net does seem like widely used).

    public ActionResult Index(
        string date
        , int? courseid = null
        , int? clubid = null
        , int? holes = null
        , int? available = null
        , int? prices = null
    )
    {
        var DateFrom = DateTime.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
    
        MTeetimes r = BookingManager.GetBookings(new Code.Classes.Params.ParamGetBooking()
        {
            ClubID = clubid
            , DateFrom = DateFrom
            , DateTo = DateFrom.AddDays(1)
            , GroundID = courseid
        });
    
        // return Json(r, JsonRequestBehavior.AllowGet);
    
        string response;
        var serializer = new DataContractJsonSerializer(typeof(MTeetimes));
    
        // Serialize
        using (var ms = new MemoryStream())
        {
            serializer.WriteObject(ms, r);
            response = Encoding.Default.GetString(ms.ToArray());
        }
    
        return Content(response);
    }
    


    [DataContract]
    public class Time
    {
        [DataMember(Name="time", EmitDefaultValue = false)]
        public string Time
        {
            get;
            set;
        }
    
        [DataMember(Name = "holes", EmitDefaultValue = false)]
        public int Holes
        {
            get;
            set;
        }
    
        [DataMember(Name = "slots_available", EmitDefaultValue = false)]
        public int Slots_available
        {
            get;
            set;
        }
    
        [DataMember(Name = "price", EmitDefaultValue = false)]
        public decimal? Price
        {
            get;
            set;
        }
    
        [DataMember(Name = "nextcourseid", EmitDefaultValue = false)]
        public int? Nextcourseid
        {
            get;
            set;
        }
    
        [DataMember(Name = "allow_extra", EmitDefaultValue = false)]
        public bool? Allow_extra
        {
            get;
            set;
        }
    }
    

提交回复
热议问题