Json.NET Ignore null values in dictionary












4















When serializing a dictionary with JSON.NET, it seems like the NullValueHandling setting is ignored.





var dict = new Dictionary<string, string>
{
["A"] = "Some text",
["B"] = null
};

var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Console.WriteLine(json);


Output:



{
"A": "Some text",
"B": null
}


I expected that only the KVP with key "A" is present in the json output and KVP "B" is omitted.



How can I tell Json.NET to only serialize the entries that do not contain null values?










share|improve this question























  • Update dict to not include null values then serialize?

    – RoadRunner
    Jan 1 at 15:48






  • 1





    Why you don't filter the dict first, just get the data not contain null value. It's easier :))

    – Tomato32
    Jan 1 at 15:50











  • As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

    – Yola
    Jan 1 at 17:35
















4















When serializing a dictionary with JSON.NET, it seems like the NullValueHandling setting is ignored.





var dict = new Dictionary<string, string>
{
["A"] = "Some text",
["B"] = null
};

var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Console.WriteLine(json);


Output:



{
"A": "Some text",
"B": null
}


I expected that only the KVP with key "A" is present in the json output and KVP "B" is omitted.



How can I tell Json.NET to only serialize the entries that do not contain null values?










share|improve this question























  • Update dict to not include null values then serialize?

    – RoadRunner
    Jan 1 at 15:48






  • 1





    Why you don't filter the dict first, just get the data not contain null value. It's easier :))

    – Tomato32
    Jan 1 at 15:50











  • As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

    – Yola
    Jan 1 at 17:35














4












4








4








When serializing a dictionary with JSON.NET, it seems like the NullValueHandling setting is ignored.





var dict = new Dictionary<string, string>
{
["A"] = "Some text",
["B"] = null
};

var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Console.WriteLine(json);


Output:



{
"A": "Some text",
"B": null
}


I expected that only the KVP with key "A" is present in the json output and KVP "B" is omitted.



How can I tell Json.NET to only serialize the entries that do not contain null values?










share|improve this question














When serializing a dictionary with JSON.NET, it seems like the NullValueHandling setting is ignored.





var dict = new Dictionary<string, string>
{
["A"] = "Some text",
["B"] = null
};

var json = JsonConvert.SerializeObject(dict, Formatting.Indented,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Console.WriteLine(json);


Output:



{
"A": "Some text",
"B": null
}


I expected that only the KVP with key "A" is present in the json output and KVP "B" is omitted.



How can I tell Json.NET to only serialize the entries that do not contain null values?







c# json.net






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 1 at 15:26









FlogexFlogex

7517




7517













  • Update dict to not include null values then serialize?

    – RoadRunner
    Jan 1 at 15:48






  • 1





    Why you don't filter the dict first, just get the data not contain null value. It's easier :))

    – Tomato32
    Jan 1 at 15:50











  • As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

    – Yola
    Jan 1 at 17:35



















  • Update dict to not include null values then serialize?

    – RoadRunner
    Jan 1 at 15:48






  • 1





    Why you don't filter the dict first, just get the data not contain null value. It's easier :))

    – Tomato32
    Jan 1 at 15:50











  • As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

    – Yola
    Jan 1 at 17:35

















Update dict to not include null values then serialize?

– RoadRunner
Jan 1 at 15:48





Update dict to not include null values then serialize?

– RoadRunner
Jan 1 at 15:48




1




1





Why you don't filter the dict first, just get the data not contain null value. It's easier :))

– Tomato32
Jan 1 at 15:50





Why you don't filter the dict first, just get the data not contain null value. It's easier :))

– Tomato32
Jan 1 at 15:50













As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

– Yola
Jan 1 at 17:35





As you already have accepted an answer, i write here to draw your attention to problem in your code. Most likely that it is illogical to not save null values from array, this means what you lose some data, with class fields that is different, because new instance will ahve this fields anyway and they will be initialized to null by default.

– Yola
Jan 1 at 17:35












3 Answers
3






active

oldest

votes


















2














I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:



using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace JsonSerialize {
public static class Program {
private static Dictionary<string, string> dict = new Dictionary<string, string> {
["A"] = "Some text",
["B"] = null
};

public static void Main (string args) {
var filtered = dict.Where (p => p.Value != null)
.ToDictionary (p => p.Key, p => p.Value);

String json = JsonConvert.SerializeObject (filtered, Formatting.Indented);

Console.WriteLine (json);
}
}
}


Which gives:



{
"A": "Some text"
}





share|improve this answer


























  • I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

    – Flogex
    Jan 1 at 17:10



















2














The NullValueHandling setting is only applicable to class properties and not dictionaries. There doesn't appear to be a built-in way in JSON.NET to ignore null values in a dictionary.



If you want JSON.NET to handle this case for you, then you can create a custom JSON converter and override the WriteJson method to handle the null values.



public class CustomJsonConverter : JsonConverter
{
public override bool CanRead => false;

public override bool CanConvert(Type objectType)
{
return objectType == typeof(Dictionary<string, string>);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var dictionary = (Dictionary<string, string>)value;

writer.WriteStartObject();

foreach (var key in dictionary.Keys)
{
if (dictionary[key] != null)
{
writer.WritePropertyName(key);

serializer.Serialize(writer, dictionary[key]);
}
}

writer.WriteEndObject();
}
}


Which then you can use like this:



var json = JsonConvert.SerializeObject(dict, Formatting.Indented, new CustomJsonConverter());





share|improve this answer































    2














    The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null by default.



    And, this would work fine for class fields if they are nulls. Look at this example:



    public class Movie
    {
    public string Name { get; set; }
    public string Description { get; set; }
    public string Classification { get; set; }
    public string Studio { get; set; }
    public DateTime? ReleaseDate { get; set; }
    public List<string> ReleaseCountries { get; set; }
    }

    Movie movie = new Movie();
    movie.Name = "Bad Boys III";
    movie.Description = "It's no Bad Boys";

    string ignored = JsonConvert.SerializeObject(movie,
    Formatting.Indented,
    new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

    // {
    // "Name": "Bad Boys III",
    // "Description": "It's no Bad Boys"
    // }


    In your case values for certain keys are nulls, but that's not the same as in the documentation provided.



    This might help you, but you should be aware of how ToDictionary affects performance:



    var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
    .ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);





    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%2f53996646%2fjson-net-ignore-null-values-in-dictionary%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using Newtonsoft.Json;

      namespace JsonSerialize {
      public static class Program {
      private static Dictionary<string, string> dict = new Dictionary<string, string> {
      ["A"] = "Some text",
      ["B"] = null
      };

      public static void Main (string args) {
      var filtered = dict.Where (p => p.Value != null)
      .ToDictionary (p => p.Key, p => p.Value);

      String json = JsonConvert.SerializeObject (filtered, Formatting.Indented);

      Console.WriteLine (json);
      }
      }
      }


      Which gives:



      {
      "A": "Some text"
      }





      share|improve this answer


























      • I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

        – Flogex
        Jan 1 at 17:10
















      2














      I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using Newtonsoft.Json;

      namespace JsonSerialize {
      public static class Program {
      private static Dictionary<string, string> dict = new Dictionary<string, string> {
      ["A"] = "Some text",
      ["B"] = null
      };

      public static void Main (string args) {
      var filtered = dict.Where (p => p.Value != null)
      .ToDictionary (p => p.Key, p => p.Value);

      String json = JsonConvert.SerializeObject (filtered, Formatting.Indented);

      Console.WriteLine (json);
      }
      }
      }


      Which gives:



      {
      "A": "Some text"
      }





      share|improve this answer


























      • I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

        – Flogex
        Jan 1 at 17:10














      2












      2








      2







      I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using Newtonsoft.Json;

      namespace JsonSerialize {
      public static class Program {
      private static Dictionary<string, string> dict = new Dictionary<string, string> {
      ["A"] = "Some text",
      ["B"] = null
      };

      public static void Main (string args) {
      var filtered = dict.Where (p => p.Value != null)
      .ToDictionary (p => p.Key, p => p.Value);

      String json = JsonConvert.SerializeObject (filtered, Formatting.Indented);

      Console.WriteLine (json);
      }
      }
      }


      Which gives:



      {
      "A": "Some text"
      }





      share|improve this answer















      I would just filter out the null values from the original dictionary with LINQ and serialize the filtered dictionary:



      using System;
      using System.Collections.Generic;
      using System.Linq;
      using Newtonsoft.Json;

      namespace JsonSerialize {
      public static class Program {
      private static Dictionary<string, string> dict = new Dictionary<string, string> {
      ["A"] = "Some text",
      ["B"] = null
      };

      public static void Main (string args) {
      var filtered = dict.Where (p => p.Value != null)
      .ToDictionary (p => p.Key, p => p.Value);

      String json = JsonConvert.SerializeObject (filtered, Formatting.Indented);

      Console.WriteLine (json);
      }
      }
      }


      Which gives:



      {
      "A": "Some text"
      }






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Jan 1 at 16:35

























      answered Jan 1 at 16:02









      RoadRunnerRoadRunner

      11.3k31341




      11.3k31341













      • I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

        – Flogex
        Jan 1 at 17:10



















      • I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

        – Flogex
        Jan 1 at 17:10

















      I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

      – Flogex
      Jan 1 at 17:10





      I am not really happy with this since I have to do this for a lot of dictionaries which may even be nested, but I guess it is still the easiest way to go. So thank you!

      – Flogex
      Jan 1 at 17:10













      2














      The NullValueHandling setting is only applicable to class properties and not dictionaries. There doesn't appear to be a built-in way in JSON.NET to ignore null values in a dictionary.



      If you want JSON.NET to handle this case for you, then you can create a custom JSON converter and override the WriteJson method to handle the null values.



      public class CustomJsonConverter : JsonConverter
      {
      public override bool CanRead => false;

      public override bool CanConvert(Type objectType)
      {
      return objectType == typeof(Dictionary<string, string>);
      }

      public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
      {
      throw new NotImplementedException();
      }

      public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
      {
      var dictionary = (Dictionary<string, string>)value;

      writer.WriteStartObject();

      foreach (var key in dictionary.Keys)
      {
      if (dictionary[key] != null)
      {
      writer.WritePropertyName(key);

      serializer.Serialize(writer, dictionary[key]);
      }
      }

      writer.WriteEndObject();
      }
      }


      Which then you can use like this:



      var json = JsonConvert.SerializeObject(dict, Formatting.Indented, new CustomJsonConverter());





      share|improve this answer




























        2














        The NullValueHandling setting is only applicable to class properties and not dictionaries. There doesn't appear to be a built-in way in JSON.NET to ignore null values in a dictionary.



        If you want JSON.NET to handle this case for you, then you can create a custom JSON converter and override the WriteJson method to handle the null values.



        public class CustomJsonConverter : JsonConverter
        {
        public override bool CanRead => false;

        public override bool CanConvert(Type objectType)
        {
        return objectType == typeof(Dictionary<string, string>);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
        throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
        var dictionary = (Dictionary<string, string>)value;

        writer.WriteStartObject();

        foreach (var key in dictionary.Keys)
        {
        if (dictionary[key] != null)
        {
        writer.WritePropertyName(key);

        serializer.Serialize(writer, dictionary[key]);
        }
        }

        writer.WriteEndObject();
        }
        }


        Which then you can use like this:



        var json = JsonConvert.SerializeObject(dict, Formatting.Indented, new CustomJsonConverter());





        share|improve this answer


























          2












          2








          2







          The NullValueHandling setting is only applicable to class properties and not dictionaries. There doesn't appear to be a built-in way in JSON.NET to ignore null values in a dictionary.



          If you want JSON.NET to handle this case for you, then you can create a custom JSON converter and override the WriteJson method to handle the null values.



          public class CustomJsonConverter : JsonConverter
          {
          public override bool CanRead => false;

          public override bool CanConvert(Type objectType)
          {
          return objectType == typeof(Dictionary<string, string>);
          }

          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
          throw new NotImplementedException();
          }

          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
          var dictionary = (Dictionary<string, string>)value;

          writer.WriteStartObject();

          foreach (var key in dictionary.Keys)
          {
          if (dictionary[key] != null)
          {
          writer.WritePropertyName(key);

          serializer.Serialize(writer, dictionary[key]);
          }
          }

          writer.WriteEndObject();
          }
          }


          Which then you can use like this:



          var json = JsonConvert.SerializeObject(dict, Formatting.Indented, new CustomJsonConverter());





          share|improve this answer













          The NullValueHandling setting is only applicable to class properties and not dictionaries. There doesn't appear to be a built-in way in JSON.NET to ignore null values in a dictionary.



          If you want JSON.NET to handle this case for you, then you can create a custom JSON converter and override the WriteJson method to handle the null values.



          public class CustomJsonConverter : JsonConverter
          {
          public override bool CanRead => false;

          public override bool CanConvert(Type objectType)
          {
          return objectType == typeof(Dictionary<string, string>);
          }

          public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
          {
          throw new NotImplementedException();
          }

          public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
          {
          var dictionary = (Dictionary<string, string>)value;

          writer.WriteStartObject();

          foreach (var key in dictionary.Keys)
          {
          if (dictionary[key] != null)
          {
          writer.WritePropertyName(key);

          serializer.Serialize(writer, dictionary[key]);
          }
          }

          writer.WriteEndObject();
          }
          }


          Which then you can use like this:



          var json = JsonConvert.SerializeObject(dict, Formatting.Indented, new CustomJsonConverter());






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 1 at 17:15









          Justin SoderstromJustin Soderstrom

          314




          314























              2














              The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null by default.



              And, this would work fine for class fields if they are nulls. Look at this example:



              public class Movie
              {
              public string Name { get; set; }
              public string Description { get; set; }
              public string Classification { get; set; }
              public string Studio { get; set; }
              public DateTime? ReleaseDate { get; set; }
              public List<string> ReleaseCountries { get; set; }
              }

              Movie movie = new Movie();
              movie.Name = "Bad Boys III";
              movie.Description = "It's no Bad Boys";

              string ignored = JsonConvert.SerializeObject(movie,
              Formatting.Indented,
              new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

              // {
              // "Name": "Bad Boys III",
              // "Description": "It's no Bad Boys"
              // }


              In your case values for certain keys are nulls, but that's not the same as in the documentation provided.



              This might help you, but you should be aware of how ToDictionary affects performance:



              var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
              .ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);





              share|improve this answer






























                2














                The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null by default.



                And, this would work fine for class fields if they are nulls. Look at this example:



                public class Movie
                {
                public string Name { get; set; }
                public string Description { get; set; }
                public string Classification { get; set; }
                public string Studio { get; set; }
                public DateTime? ReleaseDate { get; set; }
                public List<string> ReleaseCountries { get; set; }
                }

                Movie movie = new Movie();
                movie.Name = "Bad Boys III";
                movie.Description = "It's no Bad Boys";

                string ignored = JsonConvert.SerializeObject(movie,
                Formatting.Indented,
                new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

                // {
                // "Name": "Bad Boys III",
                // "Description": "It's no Bad Boys"
                // }


                In your case values for certain keys are nulls, but that's not the same as in the documentation provided.



                This might help you, but you should be aware of how ToDictionary affects performance:



                var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
                .ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);





                share|improve this answer




























                  2












                  2








                  2







                  The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null by default.



                  And, this would work fine for class fields if they are nulls. Look at this example:



                  public class Movie
                  {
                  public string Name { get; set; }
                  public string Description { get; set; }
                  public string Classification { get; set; }
                  public string Studio { get; set; }
                  public DateTime? ReleaseDate { get; set; }
                  public List<string> ReleaseCountries { get; set; }
                  }

                  Movie movie = new Movie();
                  movie.Name = "Bad Boys III";
                  movie.Description = "It's no Bad Boys";

                  string ignored = JsonConvert.SerializeObject(movie,
                  Formatting.Indented,
                  new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

                  // {
                  // "Name": "Bad Boys III",
                  // "Description": "It's no Bad Boys"
                  // }


                  In your case values for certain keys are nulls, but that's not the same as in the documentation provided.



                  This might help you, but you should be aware of how ToDictionary affects performance:



                  var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
                  .ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);





                  share|improve this answer















                  The main idea of serialization is that after deserialization you should have the same object back. Most likely that is illogical to leave out keys with null values from a dictionary because keys per se represent some data. But that is ok to not save null fields because after deserialization you would still have the same object because these fields would be initialized to null by default.



                  And, this would work fine for class fields if they are nulls. Look at this example:



                  public class Movie
                  {
                  public string Name { get; set; }
                  public string Description { get; set; }
                  public string Classification { get; set; }
                  public string Studio { get; set; }
                  public DateTime? ReleaseDate { get; set; }
                  public List<string> ReleaseCountries { get; set; }
                  }

                  Movie movie = new Movie();
                  movie.Name = "Bad Boys III";
                  movie.Description = "It's no Bad Boys";

                  string ignored = JsonConvert.SerializeObject(movie,
                  Formatting.Indented,
                  new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

                  // {
                  // "Name": "Bad Boys III",
                  // "Description": "It's no Bad Boys"
                  // }


                  In your case values for certain keys are nulls, but that's not the same as in the documentation provided.



                  This might help you, but you should be aware of how ToDictionary affects performance:



                  var json = JsonConvert.SerializeObject(dict.Where(p => p.Value != null)
                  .ToDictionary(p => p.Key, p => p.Value), Formatting.Indented);






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 1 at 17:38

























                  answered Jan 1 at 15:51









                  YolaYola

                  11.2k64672




                  11.2k64672






























                      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%2f53996646%2fjson-net-ignore-null-values-in-dictionary%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

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith