Exclude Zero Values when streaming to json with JsonResult in MVC












1















I have the Json shown below.



This is actually a far more complex object in reality, but this extract demonstrates my question.



I am looking at shrinking the size of the Json response being generated. This is currently being generated using the standard JsonResult in MVC,



Is there a way of getting JSonResult to not stream properties that have a value of 0? If that is possible, it would shrink my json response a lot! This in turn would make parsing faster.



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"thirdValue": 0.0,
"fourthValue": 30.80,
"fifthValue": 0.0
}


So I would only actually end up passing back the response below to the caller:



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"fourthValue": 30.80,
}


I have seen answers pointing me to using App_Start in my web api but I am using Kestrel which doesnt have an app start - this is being hosted by Service Fabric



protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new
{
new ServiceInstanceListener(
serviceContext =>
new KestrelCommunicationListener(
serviceContext,
(url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

return new WebHostBuilder()
.UseKestrel(options => { options.Listen(IPAddress.Any, 8081); })
.ConfigureServices(
services => services
.AddSingleton(serviceContext)
.AddSingleton(new ConfigSettings(serviceContext))
.AddSingleton(new HttpClient())
.AddSingleton(new FabricClient()))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup<Startup>()
.UseSerilog(_log, true)
.UseUrls(url)
.Build();
}))
};
}









share|improve this question

























  • Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

    – GregH
    Nov 19 '18 at 19:12











  • I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

    – Paul
    Nov 19 '18 at 19:18











  • I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

    – GregH
    Nov 19 '18 at 19:23








  • 1





    Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

    – dbc
    Nov 19 '18 at 19:40











  • Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

    – Paul
    Nov 19 '18 at 20:17
















1















I have the Json shown below.



This is actually a far more complex object in reality, but this extract demonstrates my question.



I am looking at shrinking the size of the Json response being generated. This is currently being generated using the standard JsonResult in MVC,



Is there a way of getting JSonResult to not stream properties that have a value of 0? If that is possible, it would shrink my json response a lot! This in turn would make parsing faster.



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"thirdValue": 0.0,
"fourthValue": 30.80,
"fifthValue": 0.0
}


So I would only actually end up passing back the response below to the caller:



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"fourthValue": 30.80,
}


I have seen answers pointing me to using App_Start in my web api but I am using Kestrel which doesnt have an app start - this is being hosted by Service Fabric



protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new
{
new ServiceInstanceListener(
serviceContext =>
new KestrelCommunicationListener(
serviceContext,
(url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

return new WebHostBuilder()
.UseKestrel(options => { options.Listen(IPAddress.Any, 8081); })
.ConfigureServices(
services => services
.AddSingleton(serviceContext)
.AddSingleton(new ConfigSettings(serviceContext))
.AddSingleton(new HttpClient())
.AddSingleton(new FabricClient()))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup<Startup>()
.UseSerilog(_log, true)
.UseUrls(url)
.Build();
}))
};
}









share|improve this question

























  • Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

    – GregH
    Nov 19 '18 at 19:12











  • I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

    – Paul
    Nov 19 '18 at 19:18











  • I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

    – GregH
    Nov 19 '18 at 19:23








  • 1





    Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

    – dbc
    Nov 19 '18 at 19:40











  • Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

    – Paul
    Nov 19 '18 at 20:17














1












1








1








I have the Json shown below.



This is actually a far more complex object in reality, but this extract demonstrates my question.



I am looking at shrinking the size of the Json response being generated. This is currently being generated using the standard JsonResult in MVC,



Is there a way of getting JSonResult to not stream properties that have a value of 0? If that is possible, it would shrink my json response a lot! This in turn would make parsing faster.



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"thirdValue": 0.0,
"fourthValue": 30.80,
"fifthValue": 0.0
}


So I would only actually end up passing back the response below to the caller:



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"fourthValue": 30.80,
}


I have seen answers pointing me to using App_Start in my web api but I am using Kestrel which doesnt have an app start - this is being hosted by Service Fabric



protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new
{
new ServiceInstanceListener(
serviceContext =>
new KestrelCommunicationListener(
serviceContext,
(url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

return new WebHostBuilder()
.UseKestrel(options => { options.Listen(IPAddress.Any, 8081); })
.ConfigureServices(
services => services
.AddSingleton(serviceContext)
.AddSingleton(new ConfigSettings(serviceContext))
.AddSingleton(new HttpClient())
.AddSingleton(new FabricClient()))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup<Startup>()
.UseSerilog(_log, true)
.UseUrls(url)
.Build();
}))
};
}









share|improve this question
















I have the Json shown below.



This is actually a far more complex object in reality, but this extract demonstrates my question.



I am looking at shrinking the size of the Json response being generated. This is currently being generated using the standard JsonResult in MVC,



Is there a way of getting JSonResult to not stream properties that have a value of 0? If that is possible, it would shrink my json response a lot! This in turn would make parsing faster.



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"thirdValue": 0.0,
"fourthValue": 30.80,
"fifthValue": 0.0
}


So I would only actually end up passing back the response below to the caller:



 {
"firstValue": 0.2000,
"secondValue": 30.80,
"fourthValue": 30.80,
}


I have seen answers pointing me to using App_Start in my web api but I am using Kestrel which doesnt have an app start - this is being hosted by Service Fabric



protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
{
return new
{
new ServiceInstanceListener(
serviceContext =>
new KestrelCommunicationListener(
serviceContext,
(url, listener) =>
{
ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");

return new WebHostBuilder()
.UseKestrel(options => { options.Listen(IPAddress.Any, 8081); })
.ConfigureServices(
services => services
.AddSingleton(serviceContext)
.AddSingleton(new ConfigSettings(serviceContext))
.AddSingleton(new HttpClient())
.AddSingleton(new FabricClient()))
.UseContentRoot(Directory.GetCurrentDirectory())
.UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
.UseStartup<Startup>()
.UseSerilog(_log, true)
.UseUrls(url)
.Build();
}))
};
}






c# json asp.net-mvc asp.net-core asp.net-core-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 0:14







Paul

















asked Nov 19 '18 at 19:09









PaulPaul

78831342




78831342













  • Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

    – GregH
    Nov 19 '18 at 19:12











  • I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

    – Paul
    Nov 19 '18 at 19:18











  • I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

    – GregH
    Nov 19 '18 at 19:23








  • 1





    Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

    – dbc
    Nov 19 '18 at 19:40











  • Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

    – Paul
    Nov 19 '18 at 20:17



















  • Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

    – GregH
    Nov 19 '18 at 19:12











  • I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

    – Paul
    Nov 19 '18 at 19:18











  • I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

    – GregH
    Nov 19 '18 at 19:23








  • 1





    Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

    – dbc
    Nov 19 '18 at 19:40











  • Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

    – Paul
    Nov 19 '18 at 20:17

















Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

– GregH
Nov 19 '18 at 19:12





Seems like you should be able to do this when querying the data out before returning it with a .Where(x => x.Value != 0)

– GregH
Nov 19 '18 at 19:12













I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

– Paul
Nov 19 '18 at 19:18





I dont want to do it that way because this is an object with loads of properties and that would be a huge where clause!

– Paul
Nov 19 '18 at 19:18













I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

– GregH
Nov 19 '18 at 19:23







I see. In that case you may find newtonsoft's conditional serialization interesting: newtonsoft.com/json/help/html/ConditionalProperties.htm although I believe you'll still have to define which properties you want to conditionally exclude one way or the other. I'll be interested to see if someone has a more graceful way of achieving this. Hope this helps

– GregH
Nov 19 '18 at 19:23






1




1





Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

– dbc
Nov 19 '18 at 19:40





Which version of asp.net-mvc are you using? For JSON serialization, earlier versions use JavaScriptSerializer as noted here but ASP.Net Core uses Json.NET as noted here. The answer will differ depending on the serializer.

– dbc
Nov 19 '18 at 19:40













Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

– Paul
Nov 19 '18 at 20:17





Im using ASPNet core - I am running this from inside a service fabric host which is running a Web API - I have the package Microsoft.AspNetCore.Mvc in the service

– Paul
Nov 19 '18 at 20:17












2 Answers
2






active

oldest

votes


















1














That's super easy. Just specify a value for DefaultValueHandling with the value Ignore.



As the description in that link says:




Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.







share|improve this answer
























  • Please see the startup code now added to my question, how do I integrate it in there? There is no register method

    – Paul
    Nov 20 '18 at 0:15











  • I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

    – Paul
    Nov 20 '18 at 1:17



















0














As Kit suggested, you could use the DefaultValueHandling behavior.



Besides, you can always custom your own ContractResolver to solve such questions. Here's a version of using custom ContractResolver to ignore default value:



public class IgnoreZeroContractResolver : DefaultContractResolver
{
public IgnoreZeroContractResolver( ){ }

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);

property.ShouldSerialize = instance => {
var shouldSerialize = true; // indicate should we serialize this property

var type = instance.GetType();
var pi = type.GetProperty(property.PropertyName);
var pv = pi.GetValue(instance);
var pvType = pv.GetType();

// if current value equals the default values , ignore this property
if (pv.GetType().IsValueType){
var defaultValue = Activator.CreateInstance(pvType);
if (pv.Equals(defaultValue)) { shouldSerialize = false; }
}
return shouldSerialize;
};

return property;
}

}


And now you can set your resover as the ContractResolver:



public void ConfigureServices(IServiceCollection services)
{

// ...
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(o =>{
o.SerializerSettings.ContractResolver =new IgnoreZeroContractResolver();
});

// ...

}


Test Case :



var x = new {
FirstValue =0.2000,
SecondValue= 30.80,
ThirdValue= 0.0,
FourthValue= 30.80,
FifthValue= 0.0, // double 0
SixValue= 0 // int 0
};
return new JsonResult(x);


and the response will be :



{"FirstValue":0.2,"SecondValue":30.8,"FourthValue":30.8}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381118%2fexclude-zero-values-when-streaming-to-json-with-jsonresult-in-mvc%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    That's super easy. Just specify a value for DefaultValueHandling with the value Ignore.



    As the description in that link says:




    Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.







    share|improve this answer
























    • Please see the startup code now added to my question, how do I integrate it in there? There is no register method

      – Paul
      Nov 20 '18 at 0:15











    • I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

      – Paul
      Nov 20 '18 at 1:17
















    1














    That's super easy. Just specify a value for DefaultValueHandling with the value Ignore.



    As the description in that link says:




    Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.







    share|improve this answer
























    • Please see the startup code now added to my question, how do I integrate it in there? There is no register method

      – Paul
      Nov 20 '18 at 0:15











    • I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

      – Paul
      Nov 20 '18 at 1:17














    1












    1








    1







    That's super easy. Just specify a value for DefaultValueHandling with the value Ignore.



    As the description in that link says:




    Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.







    share|improve this answer













    That's super easy. Just specify a value for DefaultValueHandling with the value Ignore.



    As the description in that link says:




    Ignore members where the member value is the same as the member's default value when serializing objects so that it is not written to JSON. This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans). The default value ignored can be changed by placing the DefaultValueAttribute on the property.








    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 19 '18 at 20:53









    KitKit

    8,87323168




    8,87323168













    • Please see the startup code now added to my question, how do I integrate it in there? There is no register method

      – Paul
      Nov 20 '18 at 0:15











    • I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

      – Paul
      Nov 20 '18 at 1:17



















    • Please see the startup code now added to my question, how do I integrate it in there? There is no register method

      – Paul
      Nov 20 '18 at 0:15











    • I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

      – Paul
      Nov 20 '18 at 1:17

















    Please see the startup code now added to my question, how do I integrate it in there? There is no register method

    – Paul
    Nov 20 '18 at 0:15





    Please see the startup code now added to my question, how do I integrate it in there? There is no register method

    – Paul
    Nov 20 '18 at 0:15













    I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

    – Paul
    Nov 20 '18 at 1:17





    I managed to get somewhere to run this code, I know it is being hit because I also set the JSON to be pretty printed. I have put DefaultValue(0) above my properties and they are still getting output?

    – Paul
    Nov 20 '18 at 1:17













    0














    As Kit suggested, you could use the DefaultValueHandling behavior.



    Besides, you can always custom your own ContractResolver to solve such questions. Here's a version of using custom ContractResolver to ignore default value:



    public class IgnoreZeroContractResolver : DefaultContractResolver
    {
    public IgnoreZeroContractResolver( ){ }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
    JsonProperty property = base.CreateProperty(member, memberSerialization);

    property.ShouldSerialize = instance => {
    var shouldSerialize = true; // indicate should we serialize this property

    var type = instance.GetType();
    var pi = type.GetProperty(property.PropertyName);
    var pv = pi.GetValue(instance);
    var pvType = pv.GetType();

    // if current value equals the default values , ignore this property
    if (pv.GetType().IsValueType){
    var defaultValue = Activator.CreateInstance(pvType);
    if (pv.Equals(defaultValue)) { shouldSerialize = false; }
    }
    return shouldSerialize;
    };

    return property;
    }

    }


    And now you can set your resover as the ContractResolver:



    public void ConfigureServices(IServiceCollection services)
    {

    // ...
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddJsonOptions(o =>{
    o.SerializerSettings.ContractResolver =new IgnoreZeroContractResolver();
    });

    // ...

    }


    Test Case :



    var x = new {
    FirstValue =0.2000,
    SecondValue= 30.80,
    ThirdValue= 0.0,
    FourthValue= 30.80,
    FifthValue= 0.0, // double 0
    SixValue= 0 // int 0
    };
    return new JsonResult(x);


    and the response will be :



    {"FirstValue":0.2,"SecondValue":30.8,"FourthValue":30.8}





    share|improve this answer




























      0














      As Kit suggested, you could use the DefaultValueHandling behavior.



      Besides, you can always custom your own ContractResolver to solve such questions. Here's a version of using custom ContractResolver to ignore default value:



      public class IgnoreZeroContractResolver : DefaultContractResolver
      {
      public IgnoreZeroContractResolver( ){ }

      protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
      {
      JsonProperty property = base.CreateProperty(member, memberSerialization);

      property.ShouldSerialize = instance => {
      var shouldSerialize = true; // indicate should we serialize this property

      var type = instance.GetType();
      var pi = type.GetProperty(property.PropertyName);
      var pv = pi.GetValue(instance);
      var pvType = pv.GetType();

      // if current value equals the default values , ignore this property
      if (pv.GetType().IsValueType){
      var defaultValue = Activator.CreateInstance(pvType);
      if (pv.Equals(defaultValue)) { shouldSerialize = false; }
      }
      return shouldSerialize;
      };

      return property;
      }

      }


      And now you can set your resover as the ContractResolver:



      public void ConfigureServices(IServiceCollection services)
      {

      // ...
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
      .AddJsonOptions(o =>{
      o.SerializerSettings.ContractResolver =new IgnoreZeroContractResolver();
      });

      // ...

      }


      Test Case :



      var x = new {
      FirstValue =0.2000,
      SecondValue= 30.80,
      ThirdValue= 0.0,
      FourthValue= 30.80,
      FifthValue= 0.0, // double 0
      SixValue= 0 // int 0
      };
      return new JsonResult(x);


      and the response will be :



      {"FirstValue":0.2,"SecondValue":30.8,"FourthValue":30.8}





      share|improve this answer


























        0












        0








        0







        As Kit suggested, you could use the DefaultValueHandling behavior.



        Besides, you can always custom your own ContractResolver to solve such questions. Here's a version of using custom ContractResolver to ignore default value:



        public class IgnoreZeroContractResolver : DefaultContractResolver
        {
        public IgnoreZeroContractResolver( ){ }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        property.ShouldSerialize = instance => {
        var shouldSerialize = true; // indicate should we serialize this property

        var type = instance.GetType();
        var pi = type.GetProperty(property.PropertyName);
        var pv = pi.GetValue(instance);
        var pvType = pv.GetType();

        // if current value equals the default values , ignore this property
        if (pv.GetType().IsValueType){
        var defaultValue = Activator.CreateInstance(pvType);
        if (pv.Equals(defaultValue)) { shouldSerialize = false; }
        }
        return shouldSerialize;
        };

        return property;
        }

        }


        And now you can set your resover as the ContractResolver:



        public void ConfigureServices(IServiceCollection services)
        {

        // ...
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(o =>{
        o.SerializerSettings.ContractResolver =new IgnoreZeroContractResolver();
        });

        // ...

        }


        Test Case :



        var x = new {
        FirstValue =0.2000,
        SecondValue= 30.80,
        ThirdValue= 0.0,
        FourthValue= 30.80,
        FifthValue= 0.0, // double 0
        SixValue= 0 // int 0
        };
        return new JsonResult(x);


        and the response will be :



        {"FirstValue":0.2,"SecondValue":30.8,"FourthValue":30.8}





        share|improve this answer













        As Kit suggested, you could use the DefaultValueHandling behavior.



        Besides, you can always custom your own ContractResolver to solve such questions. Here's a version of using custom ContractResolver to ignore default value:



        public class IgnoreZeroContractResolver : DefaultContractResolver
        {
        public IgnoreZeroContractResolver( ){ }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        property.ShouldSerialize = instance => {
        var shouldSerialize = true; // indicate should we serialize this property

        var type = instance.GetType();
        var pi = type.GetProperty(property.PropertyName);
        var pv = pi.GetValue(instance);
        var pvType = pv.GetType();

        // if current value equals the default values , ignore this property
        if (pv.GetType().IsValueType){
        var defaultValue = Activator.CreateInstance(pvType);
        if (pv.Equals(defaultValue)) { shouldSerialize = false; }
        }
        return shouldSerialize;
        };

        return property;
        }

        }


        And now you can set your resover as the ContractResolver:



        public void ConfigureServices(IServiceCollection services)
        {

        // ...
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(o =>{
        o.SerializerSettings.ContractResolver =new IgnoreZeroContractResolver();
        });

        // ...

        }


        Test Case :



        var x = new {
        FirstValue =0.2000,
        SecondValue= 30.80,
        ThirdValue= 0.0,
        FourthValue= 30.80,
        FifthValue= 0.0, // double 0
        SixValue= 0 // int 0
        };
        return new JsonResult(x);


        and the response will be :



        {"FirstValue":0.2,"SecondValue":30.8,"FourthValue":30.8}






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 10:35









        itminusitminus

        3,4261321




        3,4261321






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53381118%2fexclude-zero-values-when-streaming-to-json-with-jsonresult-in-mvc%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to change which sound is reproduced for terminal bell?

            Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

            Can I use Tabulator js library in my java Spring + Thymeleaf project?