Serialize hashtable using Json.Net

2019-06-03 22:42发布

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; }
}

1条回答
地球回转人心会变
2楼-- · 2019-06-03 23:05

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.

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.

A strongly-typed collection will resolve your Json.NET deserialization issues, as Json.NET can infer the type from the dictionary.

The use of Dictionary<TKey,TValue> over Hashtable is discussed here.

查看更多
登录 后发表回答