删除发送到JSON MVC中的对象的空属性 [英] Remove null properties of a object sent to Json MVC

查看:204
本文介绍了删除发送到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);
        }
    }
}

上面的Web服务会返回一个JSON字符串与时间的几个intance。

The webservice above returns a json string with several intance of Time.

我想要的属性Nextcourseid和allow_extra被排除在外时,他们的值都是空的输出。

I'd like properties Nextcourseid and allow_extra to be left out of the output when their values are null.

我试图ShouldSerializeXxx但它不似乎工作。

FYI:我也尝试过哪些工作,但不是有条件[ScriptIgnore]

I tried ShouldSerializeXxx but it doesn't seems to work.
FYI: I also tried [ScriptIgnore] which work but isn't conditional.

推荐答案

您不能使用默认的的Json的ActionResult 删除空的属性。

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

您可以看看<一个href=\"http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size\">JSON.NET,它可以设置删除属性的属性,如果它是空

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)]

或者,如果你不想用到其他库,你可以创建自己定制的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(); }
    }
}

现在,在您的视图:

And now in your view:

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

这篇关于删除发送到JSON MVC中的对象的空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆