首页 > 解决方案 > 将字符串转换为类型“System.Collections.Generic.Dictionary”的 Json 反序列化异常

问题描述

我有非常简单的 JSON 字符串

"{\"Region\":\"uk\"}"

我正在将它转换为这样的字典

string  data =  "{\"Region\":\"uk\"}";
var dataOut = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);

上述代码在 My Local 和 QA/UAT 环境中运行良好,但在生产服务器上出现以下错误

Newtonsoft.Json.JsonSerializationException: Error converting value "{"Region":"uk"}" to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'. Path '', line 1, position 21. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.String,System.String].
   at Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
   at Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   --- End of inner exception stack trace ---
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)

这是代码运行良好的Dotnet fiddle

Newtonsoft.Json 版本是 7.0 但

我在 QA 和 UAT 环境中的 .Net 框架版本是4.7.2558.0,但在生产环境中是4.8.3761.0

.Net Framework 4.8 是否可能是此错误的原因。

标签: c#.netjsonjson.net

解决方案


推荐阅读