NullValueHandling setting for a class on JSON.NET by JsonConverter attribute (for Azure DocumentDb)

狂风中的少年 提交于 2019-12-23 05:15:16

问题


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


回答1:


I solved it by setting the default global settings:

    JsonConvert.DefaultSettings = () => new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    };


来源:https://stackoverflow.com/questions/28499186/nullvaluehandling-setting-for-a-class-on-json-net-by-jsonconverter-attribute-fo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!