Search code examples
c#jsonserializationjson-deserialization

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


I was been working with an extension method using generics and Newtonsoft.Json's JsonConvert.DeserializeObject<TSource>(jsonString)

the serialization works as expected

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

But when trying to Deserialize

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.

now I'm used where TSource : new () on the extension method, so that any string return types would be restricted as

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

which is not letting me to use interfaces like IList, IPerson or ReadOnlyCollection on TSource

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


Solution

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

    You can use JsonSerializerSettings's TypeNameHandling property.

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