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

前端之家收集整理的这篇文章主要介绍了c# – 删除发送到Json MVC的对象的空属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. namespace Booking.Areas.Golfy.Models
  2. {
  3. public class Time
  4. {
  5. public string time { get; set; }
  6. public int holes { get; set; }
  7. public int slots_available { get; set; }
  8. public decimal? price { get; set; }
  9. public int? Nextcourseid { get; set; }
  10.  
  11. public bool ShouldSerializeNextcourseid
  12. {
  13. get
  14. {
  15. return this.Nextcourseid != null;
  16. }
  17. }
  18.  
  19. public bool? allow_extra { get; set; }
  20.  
  21. public bool ShouldSerializeallow_extra
  22. {
  23. get
  24. {
  25. return this.allow_extra != null;
  26. }
  27. }
  28. }
  29. }
  1. namespace Booking.Areas.Golfy.Controllers
  2. {
  3. public class TeetimesController : Controller
  4. {
  5. //
  6. // GET: /Golfy/Teetimes/
  7. public ActionResult Index(
  8. string date,int? courseid = null,int? clubid = null,int? holes = null,int? available = null,int? prices = null
  9. )
  10. {
  11. var DateFrom = DateTime.ParseExact(date,"yyyy-MM-dd",CultureInfo.InvariantCulture);
  12.  
  13. Teetimes r = BookingManager.GetBookings(new Code.Classes.Params.ParamGetBooking()
  14. {
  15. ClubID = clubid,DateFrom = DateFrom,DateTo = DateFrom.AddDays(1),GroundID = courseid
  16. });
  17.  
  18. return Json(r,JsonRequestBehavior.AllowGet);
  19. }
  20. }
  21. }

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

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

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

解决方法

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

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

  1. [JsonProperty(NullValueHandling=NullValueHandling.Ignore)]

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

  1. public class JsonWithoutNullPropertiesResult : ActionResult
  2. {
  3. private object Data { get; set; }
  4.  
  5. public JsonWithoutNullPropertiesResult(object data)
  6. {
  7. Data = data;
  8. }
  9.  
  10. public override void ExecuteResult(ControllerContext context)
  11. {
  12. HttpResponseBase response = context.HttpContext.Response;
  13. response.ContentType = "application/x-javascript";
  14. response.ContentEncoding = Encoding.UTF8;
  15.  
  16. if (Data != null)
  17. {
  18. JavaScriptSerializer serializer = new JavaScriptSerializer();
  19. serializer.RegisterConverters(new[] { new NullPropertiesConverter() });
  20. string ser = serializer.Serialize(Data);
  21. response.Write(ser);
  22. }
  23. }
  24. }
  25.  
  26. public class NullPropertiesConverter : JavaScriptConverter
  27. {
  28. public override IDictionary<string,object> Serialize(object obj,JavaScriptSerializer serializer)
  29. {
  30. var toSerialize = new Dictionary<string,object>();
  31.  
  32. foreach (var prop in obj.GetType()
  33. .GetProperties(BindingFlags.Instance | BindingFlags.Public)
  34. .Select(p => new
  35. {
  36. Name = p.Name,Value = p.GetValue(obj)
  37. })
  38. .Where(p => p.Value != null))
  39. {
  40. toSerialize.Add(prop.Name,prop.Value);
  41. }
  42.  
  43. return toSerialize;
  44. }
  45.  
  46. public override object Deserialize(IDictionary<string,object> dictionary,Type type,JavaScriptSerializer serializer)
  47. {
  48. throw new NotImplementedException();
  49. }
  50.  
  51. public override IEnumerable<Type> SupportedTypes
  52. {
  53. get { return GetType().Assembly.GetTypes(); }
  54. }
  55. }

现在在你看来:

  1. public ActionResult Index()
  2. {
  3. Teetimes r = BookingManager.GetBookings();
  4. return new JsonWithoutNullPropertiesResult(t);
  5. }

猜你在找的C#相关文章