我有两种方法
public static string SerializeObject<T>(T value)
{
if (value == null)
{
return null;
}
var dictionaryObject = new Dictionary<string, object> { { typeof(T).Name, value } };
var jsonString = JsonConvert.SerializeObject(dictionaryObject);
return jsonString;
}
和
public static T DeserializeObject<T>(string jsonString)
{
var objectValue = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
return JsonConvert.DeserializeObject<T>(objectValue.Values.First().ToString());
}
当我用类型
反序列化json字符串时ConcurrentDictionary<KeyValuePair<long, long>, IList<string>>
我有一个例外:
无法将字符串'[1,1]'转换为字典键类型'System.Collections.Generic.KeyValuePair`2 [System.Int64,System.Int64]'。创建TypeConverter以将字符串转换为键类型对象。路径'[1,1]',第2行,第12位。
那么有人能告诉我正确的代码吗?
这是我的代码:
var test = new ConcurrentDictionary<KeyValuePair<long, long>, IList<string>>();
test.TryAdd(new KeyValuePair<long, long>(1, 1), new List<string> { "Test" });
var se = SerializeObject(test);
var de = DeserializeObject<ConcurrentDictionary<KeyValuePair<long, long>, IList<string>>>(se);
答案 0 :(得分:3)
我不确定这是否是最好的解决方案,但是,请尝试一下:
1)按照this topic。
中的描述创建ContractResolverclass 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)改变你的序列化/反序列化方法:
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);
}
我希望,这有助于=)