I'm not sure if this is the best solution, but please try the following:
1) ContractResolver, .
class DictionaryAsArrayResolver : DefaultContractResolver
{
protected override JsonContract CreateContract(Type objectType)
{
if (objectType.GetInterfaces().Any(i => i == typeof(IDictionary) ||
(i.IsGenericType &&
i.GetGenericTypeDefinition() == typeof(IDictionary<,>))))
{
return base.CreateArrayContract(objectType);
}
return base.CreateContract(objectType);
}
}
2) Serialize/Deserialize:
public static string SerializeObject<T>(T value, JsonSerializerSettings settings)
{
if (value == null)
{
return null;
}
var dictionaryObject = new Dictionary<string, object> { { typeof(T).Name, value } };
var jsonString = JsonConvert.SerializeObject(dictionaryObject, settings);
return jsonString;
}
public static T DeserializeObject<T>(string jsonString, JsonSerializerSettings settings)
{
var objectValue = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString, settings);
return JsonConvert.DeserializeObject<T>(objectValue.Values.First().ToString(), settings);
}
3) :
[TestMethod]
public void Test()
{
var test = new ConcurrentDictionary<KeyValuePair<long, long>, IList<string>>();
test.TryAdd(new KeyValuePair<long, long>(1, 1), new List<string> { "Test" });
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ContractResolver = new DictionaryAsArrayResolver();
var se = SerializeObject(test, settings);
var de = DeserializeObject<ConcurrentDictionary<KeyValuePair<long, long>, IList<string>>>(se, settings);
}
, =)