使用 Newtonsoft.Json 的 JsonConvert.DeserializeObject<string>(jsonString) 反序列化 JSON

Deserialize JSON using Newtonsoft.Json's JsonConvert.DeserializeObject<string>(jsonString)

我一直在使用泛型和 Newtonsoft.Json 的 JsonConvert.DeserializeObject<TSource>(jsonString)

的扩展方法

序列化按预期工作

string value = string.Empty;
value = JsonConvert.SerializeObject(null);      //"null"
value = JsonConvert.SerializeObject("null");    //"null"
value = JsonConvert.SerializeObject("value");   //"value"
value = JsonConvert.SerializeObject("");        //"" 

但是在尝试反序列化时

string result = string.Empty;
result = JsonConvert.DeserializeObject("null"); //null, ok
result = JsonConvert.DeserializeObject("value"); //throwing error, expecting "value"
result = JsonConvert.DeserializeObject(""); //throwing error, expecting string.empty

Error: Unexpected character encountered while parsing value: v. Path '', line 0, position 0.

现在我在扩展方法中使用 TSource : new (),这样任何字符串 return 类型都将被限制为

public static TSource ExecuteScriptForData(this IJavaScriptExecutor javaScriptExecutor, string script, params object[] args) where TSource : new ()

这不允许我在 TSource

上使用 IListIPersonReadOnlyCollection 等界面

现在有什么方法可以配置反序列化器,以便它能够在序列化器生成时反序列化字符串?

value in json 没有任何意义。如果你希望你的结果是字符串的值,你必须把它放在 qoutes:

string result = string.Empty;
result = JsonConvert.DeserializeObject<string>("null"); //null, ok
result = JsonConvert.DeserializeObject<string>("'value'"); // "value"
result = JsonConvert.DeserializeObject<string>("''"); // string.Empty

Now Is there any way to configure the Deserializer so that it would be able to deserialize strings as Serializer is producing ?

您可以使用 JsonSerializerSettingsTypeNameHandling 属性.

var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All };

var str = JsonConvert.SerializeObject(null,settings); 
var obj1 = JsonConvert.DeserializeObject(str, settings);

str = JsonConvert.SerializeObject("value", settings);
var obj2 = JsonConvert.DeserializeObject(str, settings);

str = JsonConvert.SerializeObject("", settings);
var obj3 = JsonConvert.DeserializeObject(str, settings);