当我有2种方法异常反序列化JSON
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>>
我有一个例外:
Co uld不会将字符串'[1,1]'转换为字典键类型'System.Collections.Generic.KeyValuePair`2 [System.Int64,System.Int64]'。创建一个TypeConverter将字符串转换为键类型对象。 Path'[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);
为什么你把它变成一个字典? – Toxicable
你可能需要更多地解释你想要完成的事情。不知道你想用Dictionary来解决什么问题。 – d512
@ user1334007:我想反序列化一个JSON字符串到类型为ConcurrentDictionary的对象,IList > –