在JsonConverter中递归调用JsonSerializer

Dav*_*fer 14 .net c# serialization json json.net

我正在编写一个JsonConverter执行一些我需要在读/写上完成的转换任务.特别是,我正在采用现有的序列化行为,并在读取时读取/读取这些附加属性时添加一些其他属性.

在里面JsonConverter,我想利用传递的JsonSerializer实例来执行大部分转换功能.然而,当我这样做时,我最终进入一个递归循环,其中串行器调用我的转换器调用串行器调用转换器等.

我见过人们做的事情,比如使用JsonConvert.SerializeObject,传递序列化程序实例中的所有转换器,除了 this.但是,这对我不起作用,因为它绕过了我在序列化程序上完成的所有其他自定义,例如自定义合同解析器和DateTime处理.

有没有办法可以:

  1. 使用传递给我的序列化程序实例,但不知何故排除我的转换器,或
  2. 克隆传递给我的序列化程序(无需手动构建新的并按属性复制属性)并删除我的转换器?

And*_*ook 6

这是一个很常见的问题。使用“JsonConvert.SerializeObject”并不是一个坏主意。但是,在某些情况下(通常是集合)可以使用的一个技巧是在写入时转换为接口,并在读取时反序列化为简单的派生类。

下面是一个简单的转换器,它处理可能已被序列化为一组 KVP 而不是看起来像一个对象的字典(在这里显示我的年龄 :))

注意“WriteJson”转换为 IDictionary<K,V> 并且“ReadJson”使用“DummyDictionary”。您最终得到了正确的结果,但使用了传递的序列化程序而不会导致递归。

/// <summary>
/// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
/// </summary>
public class DictionaryAsKVPConverter<TKey, TValue> : JsonConverter
{
    /// <summary>
    /// Determines whether this instance can convert the specified object type.
    /// </summary>
    /// <param name="objectType">Type of the object.</param>
    /// <returns>
    ///     <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
    /// </returns>
    public override bool CanConvert(Type objectType)
    {
        if (!objectType.IsValueType && objectType.IsGenericType)
            return (objectType.GetGenericTypeDefinition() == typeof(Dictionary<,>));

        return false;
    }

    /// <summary>
    /// Writes the JSON representation of the object.
    /// </summary>
    /// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
    /// <param name="value">The value.</param>
    /// <param name="serializer">The calling serializer.</param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var dictionary = value as IDictionary<TKey, TValue>;
        serializer.Serialize(writer, dictionary);
    }

    /// <summary>
    /// Reads the JSON representation of the object.
    /// </summary>
    /// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
    /// <param name="objectType">Type of the object.</param>
    /// <param name="existingValue">The existing value of object being read.</param>
    /// <param name="serializer">The calling serializer.</param>
    /// <returns>The object value.</returns>
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        Dictionary<TKey, TValue> dictionary;

        if (reader.TokenType == JsonToken.StartArray)
        {
            dictionary = new Dictionary<TKey, TValue>();
            reader.Read();
            while (reader.TokenType == JsonToken.StartObject)
            {
                var kvp = serializer.Deserialize<KeyValuePair<TKey, TValue>>(reader);
                dictionary[kvp.Key] = kvp.Value;
                reader.Read();
            }
        }
        else if (reader.TokenType == JsonToken.StartObject)
            // Use DummyDictionary to fool JsonSerializer into not using this converter recursively
            dictionary = serializer.Deserialize<DummyDictionary>(reader);
        else
            dictionary = new Dictionary<TKey, TValue>();

        return dictionary;
    }

    /// <summary>
    /// Dummy to fool JsonSerializer into not using this converter recursively
    /// </summary>
    private class DummyDictionary : Dictionary<TKey, TValue> { }
}
Run Code Online (Sandbox Code Playgroud)