Remove null properties of an object sent to Json MVC

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


        
3条回答
  •  借酒劲吻你
    2020-12-17 19:32

    I always had problems with framework-embedded json serializer, therefore I use Json.NET. Here's little example testing these two serializers:

    public class Model {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public bool ShouldSerializeName() {
            return Name != null;
        }
    }
    
    class Program {
        static void Main(string[] args) {
            var t1 = new Model {
                Name = "apw8u3rdmapw3urdm",
                Id = 298384
            };
            var t2 = new Model {
                Id = 234235
            };
    
            Test(t1);
            Test(t2);
        }
    
        static void Test(Model model) {
            Console.WriteLine("JSon from .Net: {0}", ToJson(model));
            Console.WriteLine("JSon from JSon.Net: {0}", ToDotNetJson(model));
        }
    
        static string ToJson(Model model) {
            var s = new JavaScriptSerializer();
            return s.Serialize(model);
        }
    
        static string ToDotNetJson(Model model) {
            return JsonConvert.SerializeObject(model);
        }
    }
    

    You have to include System.Web.Extensions as dependency and install Json.Net with nuget to have the example working.

    Here's some documentation form Json.NET and Framework-embedded serializer

提交回复
热议问题