c# – 删除发送到Json MVC的对象的空属性

前端之家收集整理的这篇文章主要介绍了c# – 删除发送到Json MVC的对象的空属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
namespace Booking.Areas.Golfy.Models
{
    public class Time
    {
        public string   time            { get; set; }
        public int      holes           { get; set; }
        public int      slots_available { get; set; }
        public decimal? price           { get; set; }
        public int?     Nextcourseid    { get; set; }

        public bool ShouldSerializeNextcourseid
        {
            get
            {
                return this.Nextcourseid != null;
            }
        }

        public bool? allow_extra { get; set; }

        public bool ShouldSerializeallow_extra
        {
            get
            {
                return this.allow_extra != null;
            }
        }
    }
}
namespace Booking.Areas.Golfy.Controllers
{
    public class TeetimesController : Controller
    {
        //
        // GET: /Golfy/Teetimes/
        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);

            Teetimes r = BookingManager.GetBookings(new Code.Classes.Params.ParamGetBooking()
            {
                ClubID = clubid,DateFrom = DateFrom,DateTo = DateFrom.AddDays(1),GroundID = courseid
            });

            return Json(r,JsonRequestBehavior.AllowGet);
        }
    }
}

上面的webservice返回一个json字符串与几个意思的时间.

我希望属性Nextcourseid和allow_extra在其值为null时被遗漏在输出之外.

我尝试了ShouldSerializeXxx但似乎没有工作.
FYI:我也尝试[ScriptIgnore]哪个工作,但不是有条件的.

解决方法

您不能使用默认Json ActionResult来删除属性.

您可以看一下JSON.NET,它有一个属性,您可以设置为删除属性(如果为空)

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

或者如果您不想使用其他库,您可以创建自己的json自定义ActionResult并为默认的JavaScriptSerializer注册一个新的转换器,如下所示:

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<string,object> Serialize(object obj,JavaScriptSerializer serializer)
    {
        var toSerialize = new Dictionary<string,object>();

        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<string,object> dictionary,Type type,JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override IEnumerable<Type> SupportedTypes
    {
        get { return GetType().Assembly.GetTypes(); }
    }
}

现在在你看来:

public ActionResult Index()
{
    Teetimes r = BookingManager.GetBookings();
    return new JsonWithoutNullPropertiesResult(t);
}
原文链接:https://www.f2er.com/csharp/93749.html

猜你在找的C#相关文章