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);
}
}
}
The webservice above returns a json string with several intance of Time.
I'd like properties Nextcourseid and allow_extra to be left out of the output when their values are null.
I tried ShouldSerializeXxx but it doesn't seems to work.
FYI: I also tried [ScriptIgnore] which work but isn't conditional.
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).
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
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:And now in your view:
I always had problems with framework-embedded json serializer, therefore I use Json.NET. Here's little example testing these two serializers:
You have to include
System.Web.Extensions
as dependency and installJson.Net
with nuget to have the example working.Here's some documentation form Json.NET and Framework-embedded serializer