Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing properties with null values

In my DocumentDb documents, I don't want to include properties with NULL values. For example, I have the following POCO class.

public class Person
{
   [JsonProperty(PropertyName="id")]
   public int PersonId {get; set;}

   [JsonProperty(PropertyName="firstName")]
   public string FirstName {get; set;}

   [JsonProperty(PropertyName="middleName")]
   public string MiddleName {get; set;}

   [JsonProperty(PropertyName="lastName")]
   public string LastName {get; set;}
}

Some people don't have middle names and when I save a person's document in my collection, I don't want the middle name to be included. Currently, a person without a middle name is saved as:

{
   "id": 1234,
   "firstName": "John",
   "middleName": null,
   "lastName": "Smith"
}

Is this normal behavior? If not, how do I NOT include the middle name property with a NULL value in my document?

P.S. All serialization/deserialization is handled by JSON.NET

like image 935
Sam Avatar asked Jan 09 '23 19:01

Sam


1 Answers

You can do that when you initialize the Cosmos Client, there's a serialization option which is similar to the JSON.Net.

CosmosClient client = new CosmosClient(yourConnectionString, new CosmosClientOptions()
                {
                    SerializerOptions = new CosmosSerializationOptions()
                    {
                        IgnoreNullValues = true,
                    }
                });
like image 179
Elie Tebchrani Avatar answered Jan 19 '23 01:01

Elie Tebchrani