Dipon Roy
Dipon Roy

Reputation: 406

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 ?

Upvotes: 1

Views: 4362

Answers (2)

EZI
EZI

Reputation: 15354

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

Upvotes: 2

alisabzevari
alisabzevari

Reputation: 8126

value in json does not have any meanings. If you expect your result to be the value of string you have to put it in qoutes:

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

Upvotes: 1

Related Questions