Insert non-nulls only(SDK .Net 2.7, server 6.0.4)

Hi,

We have a requirement to insert the data to Couchbase with only the non-null values.

We’re using .Net 2.7 SDK with server 6.0.4. The POCO has a lot of fields that might be null and we need to eliminate them from the JSON.

Example:

POCO:
public class User {
public string Name { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

Data:
{
“firstName”: null,
“lastName”: null,
“fullName”: “Harry Potter”
}

Expected Couchbase Document After Insert
{
“fullName”: “Harry Potter”
}

We’re using “bucket.insert” to insert the document.

Is there a way to handle it using the Couchbase SDK?
Request you to please help me out ith this.

If you are using the default Newtonsoft.Json serializer, then you can suppress these properties using a couple of different methods.

First, on a per-property basis:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Name { get; set; }

At the class level:

[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
public class User
{
    /// ...
}

Or you may change the default globally by setting the serializer during bootstrap:

var serializerSettings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    NullValueHandling = NullValueHandling.Ignore
};

var config = new ClientConfiguration
{
    Serializer = () => new DefaultSerializer(serializerSettings, serializerSettings)
};

var cluster = new Cluster(config);

My apologies for any slight typos, I wrote this from memory. But the gist of it should be correct.

2 Likes

@btburnett3,

Thanks a ton for responding.
It helped.

Stay safe!