這是一個非常普遍的問題。使用「JsonConvert.SerializeObject」不是一個壞主意。然而,在某些情況下(通常爲集合)可以使用的一種技巧是在寫入時將接口轉換爲接口,並在讀取時將反序列化轉換爲簡單的派生。
下面是一個簡單的轉換器,與可能已係列化爲一組KVPs,而不是看起來像一個對象字典優惠(顯示我的年齡在這裏:))
注「WriteJson」強制轉換成IDictionary的<ķ ,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> { }
}
這並不回答被問到的問題。問題不是「我如何使用'JsonConvert'序列化我的對象?」這是問如何避免從一個自定義的'JsonConverter'中的遞歸循環。請注意['JsonConvert'](http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonConvert.htm)和['JsonConverter'](http://www.newtonsoft.com/json/help/html /T_Newtonsoft_Json_JsonConverter.htm)是Json.Net中兩個完全不同的類。 –