问题
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:
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.
回答2:
Here's a generic static extension method that I wrote to help me with this problem. I basically wanted this code to never blow up even if the data is somehow corrupted.
public static T Read<T>(this Hashtable hash, string key)
{
if (!hash.ContainsKey(key))
return default;
if (hash[key] is T)
return (T)hash[key];
if (hash[key] is JToken token)
return token.ToObject<T>();
try
{
return (T)Convert.ChangeType(hash[key], typeof(T));
}
catch (InvalidCastException)
{
Debug.LogWarning($"{key} had the wrong type of {hash[key].GetType()}");
return default;
}
}
来源:https://stackoverflow.com/questions/27939880/serialize-hashtable-using-json-net