I have several DAO files, which are stored in Azure DocumentDb, and now I want that the null values won't be stored in the DocDb, it is possible by the [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
attribute for properties. But I don't wan't to put such attribute on every property.
The problem is, there isn't any way to set the JsonSerializerSettings
for the Json serializer used by the Azure DocumentDb API.
The way which seems for me to go, is to use the JsonConverter
attribute on a class, and create a custom JsonConverter
class which will use standard serialization but with changing the serialization settings.
That's the converter:
public class CommonJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JObject.ReadFrom(reader);
return token.ToObject(objectType, serializer);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.NullValueHandling = NullValueHandling.Ignore;
var jo = JObject.FromObject(value, serializer);
jo.WriteTo(writer);
}
}
but I get on WriteJson such exception:
A first chance exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Additional information: Self referencing loop detected with type 'Infrastructure.Dao.Contacts.PersonDao'. Path ''.
I tried to change the WriteJson function to:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var jo = JObject.FromObject(value, new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore });
jo.WriteTo(writer);
}
but then I get:
An unhandled exception of type 'System.StackOverflowException' occurred in Newtonsoft.Json.dll