Json.NET:反序列化嵌套字典
将对象反序列化为Dictionary
( JsonConvert.DeserializeObject<IDictionary>(json)
)时,嵌套对象被反序列JObject
s。 是否可以强制嵌套对象反序列化为Dictionary
?
我找到了一种方法Dictionary
通过提供CustomCreationConverter
实现将所有嵌套对象转换为Dictionary
:
class MyConverter : CustomCreationConverter> { public override IDictionary Create(Type objectType) { return new Dictionary(); } public override bool CanConvert(Type objectType) { // in addition to handling IDictionary // we want to handle the deserialization of dict value // which is of type object return objectType == typeof(object) || base.CanConvert(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null) return base.ReadJson(reader, objectType, existingValue, serializer); // if the next token is not an object // then fall back on standard deserializer (strings, numbers etc.) return serializer.Deserialize(reader); } } class Program { static void Main(string[] args) { var json = File.ReadAllText(@"c:\test.json"); var obj = JsonConvert.DeserializeObject>( json, new JsonConverter[] {new MyConverter()}); } }
文档: 带有Json.NET的CustomCreationConverter
替代/更新:
我需要反序列化String
的词典字典,并使用当前的Json.NET(5.0)我不必创建CustomConverter,我刚刚使用(在VB.Net中):
JsonConvert.DeserializeObject(Of IDictionary(Of String, IDictionary(Of String, String)))(jsonString)
或者,在C#中:
JsonConvert.DeserializeObject>(jsonString);