使用Json.Net序列化哈希表 [英] Serialize hashtable using Json.Net
问题描述
我有一个哈希表,其键的类型为整数,但是当使用json.net反序列化时,键又以字符串形式返回,有没有办法使用json.net序列化/反序列化将键类型保留在哈希表上?该哈希表是"MyType"类型的属性
I have a hashtable whose keys are of type integer, however when deserializing using json.net the keys come back as strings, is there a way to keep the key type on hashtable using json.net serialization/deserialization? This hashtable is a property of the type 'MyType'
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
string json = JsonConvert.SerializeObject(o, Formatting.Indented, settings);
mo = JsonConvert.DeserializeObject<MyType>(json, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
public Hashtable jsonViews
{
get { return mViews; }
set { mViews = value; }
}
推荐答案
问题是System.Collections.Hashtable
的类型不是很强-它可以容纳任何类型的对象,并且JSON.NET最有可能序列化字符串表示形式您的哈希表内容.
The problem is that the System.Collections.Hashtable
isn't strongly typed - it will hold any type of object, and JSON.NET is most likely serialising the string representation of your hashtable contents.
在花太多时间按摩JSON.NET序列化器/反序列化器以弥补这一点之前,您可能需要考虑将Hashtable
换成Dictionary<TKey, TValue>
.就性能而言,它几乎是相同的,但是却为您提供了强类型集合的优势和安全性.
Before you spend too much time massaging the JSON.NET serializer/deserializer to compensate for this, you might want to consider switching your Hashtable
out for a Dictionary<TKey, TValue>
. It's almost identical in terms of performance, but gives you the advantage and safety of a strongly-typed collection.
强类型集合可以解决您的Json.NET反序列化问题,因为Json.NET可以从字典中推断类型.
A strongly-typed collection will resolve your Json.NET deserialization issues, as Json.NET can infer the type from the dictionary.
在Hashtable
上使用Dictionary<TKey,TValue>
在这里讨论.
这篇关于使用Json.Net序列化哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!