title: Stop Gson from serializing object in list
body: <p>When serializing a list of Java objects with Gson, I want the objects to be filtered so that only objects with certain values in a status field are serialized. So far I have come up with using two Gson instances, one with a custom serializer, one without</p>
  
  <pre><code>...
  gson = gsonBuilder.create();
  
  gsonBuilder.registerTypeAdapter(PropertyValue.class, new PropertyValueSerializer());
  strictGson = gsonBuilder.create();
  </code></pre>
  
  <p>where PropertyValueSerializer looks like this:</p>
  
  <pre><code>public static class PropertyValueSerializer implements JsonSerializer&lt;PropertyValue&gt; {
      @Override
      public JsonElement serialize(PropertyValue propertyValue, Type typeOfT, JsonSerializationContext context) {
          PropertyStatus propertyStatus = propertyValue.getStatus();
          if (propertyStatus == null || propertyStatus.isIndex()) {
              return gson.toJsonTree(propertyValue);
          } else {
              return null;
          }
      }
  }
  </code></pre>
  
  <p>That is, use default serialization or return null if the status field indicates that the PropertyValue should not be serialized. This executes, but returning null obviously doesn't work for excluding the PropertyValue object from serialization as I get JSON like this:</p>
  
  <pre><code>[
  
      {
          "status": "HasDraft",
          "sourceInfo": {
              "author": "UUU",
              "refId": "6aad7da8-e635-461d-8d42-c9a8aecd61fc"
          },
          "valueType": "TEXT",
          "value": {
              "sv": "Rojo"
          }
      },
      null
  ]
  </code></pre>
  
  <p>Is there a way to exclude the second PropertyValue object so I get</p>
  
  <pre><code>[
  
      {
          "status": "HasDraft",
          "sourceInfo": {
              "author": "UUU",
              "refId": "6aad7da8-e635-461d-8d42-c9a8aecd61fc"
          },
          "valueType": "TEXT",
          "value": {
              "sv": "Rojo"
          }
      }
  ]
  </code></pre>