title: JSON.NET serialize JObject while ignoring null properties
body: <p>I have a <code>JObject</code> which is used as a <strong>template</strong> for calling RESTful web services. This <code>JObject</code> gets created via a parser and since it's used as a template telling the user what the endpoint schema looks like, I had to figure out a way to preserve all properties, which is why I'm defaulting their values to <code>null</code>. As as example, this is what the object originally looks like: </p>
  
  <pre><code>{  
     "Foo":{  
        "P1":null,
        "P2":null,
        "P3":null,
        "P4":{  
           "P1":null,
           "P2":null,
           "P3":null,
        },
        "FooArray":[  
           {  
              "F1":null,
              "F2":null,
              "F3":null,
           }
        ]
     },
     "Bar":null
  }
  </code></pre>
  
  <p>The user is then able to fill in individual fields as they need, such as <code>Foo.P2</code> and <code>Foo.P4.P1</code>:</p>
  
  <pre><code>{  
     "Foo":{  
        "P1":null,
        "P2":"hello world",
        "P3":null,
        "P4":{  
           "P1":1,
           "P2":null,
           "P3":null,
        },
        "FooArray":[  
           {  
              "F1":null,
              "F2":null,
              "F3":null,
           }
        ]
     },
     "Bar":null
  }
  </code></pre>
  
  <p>meaning they only care about those two fields. Now I want to serialize this template (<code>JObject</code>) back to a JSON string, but want only those fields that are populated to show up. So I tried this:</p>
  
  <pre><code>string json = JsonConvert.SerializeObject(template,
      new JsonSerializerSettings
      {
          NullValueHandling = NullValueHandling.Ignore
      });
  </code></pre>
  
  <p>Unfortunately, this didn't work. I came across <a href="https://stackoverflow.com/questions/29258587/newtonsoft-json-net-serialize-jobject-doesnt-ignore-nulls-even-with-the-right">this question</a> and realized that a <code>null</code> value in the object is an actual <code>JToken</code> type and not really a <code>null</code>, which makes sense. However, in this very particular case, I need to be able to get rid of these "unused" fields. I tried manually iterating over nodes and removing them but that didn't work either. Note that the only managed type I'm using is <code>JObject</code>; I don't have a model to convert the object to or define attributes on, since this "template" gets resolved at runtime. I was just wondering if anyone has encountered a problem like this and has any insights. Any help is greatly appreciated!</p>